Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between struct {0} and memset 0 [duplicate]

Tags:

c

struct

Assume we have struct like this:

struct A
{
    int x;
    int y;
};

what is the difference between

A a = {0};

and

A a;
memset(&a,0,sizeof(A));
like image 234
Avi Moraly Avatar asked Dec 25 '12 15:12

Avi Moraly


People also ask

Is 0 same as memset?

In this case writing a POD_OnlyStruct t = {} or POD_OnlyStruct t; memset(&t, 0, sizeof t) doesn't make much difference, as the only difference we have here is the alignment bytes being set to zero-value in case of memset used. Since you don't have access to those bytes normally, there's no difference for you.

What can be used instead of memset?

For one thing, sizeof(my_array) returns the total number of bytes in the data structure and not the number of elements.


2 Answers

None. The final outcome is that both initialize structure members to 0.

C99 Standard 6.7.8.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.

Your structure A is an aggregate and above rule applies to it. So all the structure members are initialized with value same as for static storage duration. Which is 0.

C99 Standard 7.21.6.1 The memset function:

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

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

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

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

In either case you do not have access to the alignment/padding bytes through convention language constructs and hence both get you the same effect.

like image 179
Alok Save Avatar answered Sep 17 '22 20:09

Alok Save


Both are setting memory to 0

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

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

And you could not do it in this way:

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 could do also

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

Another thing

when using memset to set your memory to 0, here your are calling a function (and this take time). And when setting with {0}, you are not calling a function. So the {0} could be faster than memset

like image 32
MOHAMED Avatar answered Sep 21 '22 20:09

MOHAMED