I declared a struct and I want to check if it has been initialized yet. How do I do this?
I've tried:
struct mystruct str1;
if(str1 != NULL)
if(str1->name != NULL)
The struct is a linked list, and also contains properties of type int and char among others.
If you declare the struct outside of any function including main()
, the struct and its contents will be initialized to zero. As pointed out in the comments, that means different things for different data types.
If you define the struct or any variables non-static within a function, they are undefined. On some implementations they happen to contain whatever is on the stack in many implementations, but that is architecture-dependent. In any case, you can assume structs, arrays and variables that are declared in a function without the static word in front of them are uninitialized and contain garbage.
You normally would not test to see if a struct is initialized, you just have to know the circumstances you defined the in, and whether you've initialized it (and its subelements) or not.
The only way you could determine if a struct was initialized would be to check each element within it to see if it matched what you considered an initialized value for that element should be. If you want to check to see if a pointer to a struct is initialized to a pre-defined state, you'd just see if it contains either NULL or a specific address you initialized it to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With