What is the correct way to initialize a very large struct?

memset is the way to go. You do not have many alternatives.

Do something like:

#define InitStruct(var, type) type var; memset(&var, 0, sizeof(type))

So that you only have to:

InitStruct(st, BigStruct);

And then use st as usual...

I do not get how "0" is not a valid "0" type for a struct. The only way to "mass initialize" a struct is to set all of its memory to a value; otherwise you would have to make extra logic to tell it to use a specific bit pattern per member. The best "generic" bit pattern to use is 0.

Besides - this is the same logic that you used when doing

*(controller->bigstruct) = *( struct bigstruct ){ 0 };

Therefore I don't get your reluctance to use it :)

The first comment to this post made me do some research before I called him and idiot and I found this:

http://www.lysator.liu.se/c/c-faq/c-1.html

Very interesting; if I could vote-up a comment I would :)

That being said - your only option if you want to target archaic architectures with non-0 null values is still to do manual initialization to certain members.

Thanks Thomas Padron-McCarthy! I learned something new today :)


If you don't want to use memset, you could always declare a static copy of your struct and use memcpy, which will give similar performance. This will add 4 megs to your program but is probably better than setting individual elements.

That said, if GCC was using memset, and it was good enough previously, I would suggest it is good enough now.

Tags:

C

Struct