views:

113

answers:

2

I am back into c/Linux. The question might look stupid, but relevant after working in c# etc.

I have some structures inside structures and the hierarchy level is more than 5. In such a case, I am doing an initialisation of every structure at the beginning explicitly. I know c does not have a new() method that will do it for you. Now I wish to know if there is any tool/widget that might create this code of initiating the structures for me. Its a tedious job and can speed up my work.

+1  A: 

If all you want to do is to initialize everything to zeroes, you can initialize your struct with {0}, which is always going to initialize everything to 0.

From the C standard, 6.7.8 (emphasis mine):

20. If the aggregate or union contains elements or members that are aggregates or unions, these rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. Otherwise, only enough initializers from the list are taken to account for the elements or members of the subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next element or member of the aggregate of which the current subaggregate or contained union is a part.

21. If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

In plain terms, {0} is the correct initializer for any aggregate type. So, struct foo bar = { 0 }; initializes the first element of bar to 0, and the rest are initialized recursively to their respective zero values.

If you want to initialize the members to non-zero values, you may want to write a function. Note that the "zero" value is correct for each data type. This may not be all-bits-zero for pointers and/or floating-point values.

gcc with -Wall option by default warns if you don't have "enough" braces, but the warning is harmless if you know what you're doing. You can disable the with -Wno-missing-braces

Alok
If you want to initialize the members to non-zero values, you could make one global constant structure and assign that. That way you can re-initialize a structure later with ease.
Chris Lutz
+1  A: 

You can use calloc function to initialize all memory to zero .

calloc() allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero.

pavun_cool