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));
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.
For one thing, sizeof(my_array) returns the total number of bytes in the data structure and not the number of elements.
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 firstn
characters of the object pointed to bys
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With