Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a struct is initialized in C?

Tags:

c

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.

like image 706
User Avatar asked Feb 10 '23 13:02

User


1 Answers

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.

  1. integers (e.g. char, short, int, long, unsigned, unsigned int, long long, etc..) will be 0
  2. float and double will be numeric 0.0 [but the bytes they are comprised of may not be]
  3. pointers will be NULL
  4. struct padding may be undefined.
  5. arrays will be zeroed as appropriate for their type.

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.

like image 168
clearlight Avatar answered Feb 13 '23 04:02

clearlight