Domanda

I need to set an array of structures to 0 after declaration. I can do it by

main()
{
    struct data dataarray[100];
    memset(dataarray,0x00,sizeof(dataarray));
}

But what if i do it like below

main()
{
   struct data dataarray[100] = {0}
}

If i use memset() it is taking too much time to complete. I need to optimize this function. So can i use second method to set memory to 0 ? Is second method guarantees that all memory is initialized to 0 ?

È stato utile?

Soluzione

There is no practical difference between the two methods in the code posted. In either case you set the whole struct to zero (including any padding bytes). In either case, the code doing this is executed in "runtime", when the program enters main().

There would have been a significant difference between the former (memset version) and the latter (initialization), had the struct been declared at file scope or as static. In that case, it would have static storage duration and since it is set to zero, it would be allocated in a memory segment called .bss, where the struct would have been set to zero before the program started.


Regarding initialization of struct padding bytes: the C standard guarantees that if an "aggregate" (meaning an array or a struct or a union) does not have all of its members explicitly initialized, it will set them all to zero. This includes padding.

C11 6.7.9 §21

"If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate..." /-/ "...the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And then we can check how a a struct with static storage duration is initialized:

C11 6.7.9 §10

"If an object that has static or thread storage duration is not initialized explicitly, then:" /--/

  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

So no matter if you write dataarray[100] = {0} or memset, the complete aggregate, including any padding, is guaranteed to be set to zero.

Altri suggerimenti

Anything in C can be initialised with = 0; this initialises numeric elements to zero and pointers null. Also please look http://ex-parrot.com/~chris/random/initialise.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top