What is the difference between struct {0} and memset 0

Possible duplicate:
Which one to use - memset () or initialization of the value to nullify the structure?

Suppose we have a structure like this:

struct A { int x; int y; }; 

What's the difference between

 A a = {0}; 

and

 A a; memset(&a,0,sizeof(A)); 
+7
source share
2 answers

Missing. The end result is that both initialize the members of the structure to 0 .

C99 Standard 6.7.8.21

If the list enclosed in brackets contains fewer initializers than the element or elements of the collection or fewer characters in the string literal used to initialize an array with a known size than in the array, the rest of the aggregate must be initialized implicitly in the same way as objects, having a static storage duration.

Your structure A is aggregating, and the above rule applies to it. Thus, all elements of the structure are initialized with the same accuracy as for the static storage duration. This is 0 .

C99 Standard 7.21.6.1 memset function:

 void *memset(void *s, int c, size_t n); 

The memset function copies the value of c (converted to unsigned char) to each of the first n characters of the object pointed to by s .

In simple words, all members, including the alignment / padding bits in the object of your structure A , are set to 0 .

Note that the difference between the two constructs in C is that memset also sets the alignment / padding to 0 , while aggregate initialization only guarantees that your structure members are set to 0 .

In any case, you do not have access to alignment / padding bytes through the conventions language constructs and, therefore, both effects will get the same effect.

+10
source

Both set memory to 0

The first is used to set only the static allocation memory to 0

 A a ={0}; // set a staic memory to 0 

And you could not do it like this:

 A *a = malloc(sizeof(A)); a = {0} // This could not be done 

The second is used to set both dynamic and static allocation memory to 0

 A a; memset(&a,0,sizeof(A)); 

And you can also do

 A *a = malloc(sizeof(A)); memset(a,0,sizeof(A)); 

Another thing

when using memset to set your memory to 0 , you call the function here (and it takes time). And when setting with {0} you do not call the function. Thus, {0} can be faster than memset

+4
source

All Articles