Reputation: 1
struct abc
{
float b;
};
abc* xyz;
xyz->b = 10;
printf("%f", xyz->b);
error at printf. What is the reason? How can I solve this?
Upvotes: 0
Views: 232
Reputation: 13076
In code :
#include <iostream>
struct abc
{
float b = 0.0f; // initialize!
};
int main()
{
abc* xyz = new abc{}; // <-- new!
// or use auto xyz = std::make_unique<abc>(); <-- recommended for c++
xyz->b = 10.0f;
std::cout << xyz->b;
// printf("%f", xyz->b); <-- std::cout is more 'c++'
delete xyz;
}
Upvotes: 1
Reputation: 41
You need to define an instance of structure.
abc *xyz
only defines a pointer, it doesn't allocate memory(static or dynamic) for an instance of struct abc
. Hence variable float b
is not allocated space.
Solution:
abc xyz;
xyz.b=10;
Or
abc *xyz = new abc;
Upvotes: 4
Reputation: 1714
One possible solution is to just change:
abc *xyz;
into
abc *xyz = new abc();
The reason for the crash is that you did not allocate any actual memory for abc::b
, thus xyz
is an uninitialized pointer.
Upvotes: 0