Although the effect is to set the contents of the array a[] to zero. However, the two pieces of code are used in completely different situations and cannot be replaced by each other:
char a[100] = {0} declares and initializes array variables. Before that a[] didn’t exist.
memset(a, 0, sizeof(a)) is to clear its contents after a[] has been declared previously. a[] existed before this.
Also, memset is a library function, not a capability of the language itself.
One is to fill a with character 0 (0x30) and the other is to use 0. And C99 seems to automatically add '0' memset does not. Its meaning is to fill a certain area of an address with the specified content
a[100] = {0}; can be regarded as syntactic sugar to quickly initialize variable memory for easy coding. It is only executed once when entering the scope. Of course, the scope can be executed again when entering the scope repeatedly. Memset is a general function for setting memory and can be called at any time.
char a[100] = {0} is statically initialized to 0, and the corresponding memory is 0 before the program runs memset() is dynamically initialized to 0, and the corresponding memory is cleared when the program runs
Initialize
a[0]
to'0'
, and initialize subsequent element values to 0, that is, 'there is a bar 0 here'. (The bar cannot come out)If it is
The first element is initialized with 'bar 0', and subsequent elements are still value-initialized.
and
is equivalent to
Although the effect is to set the contents of the array
a[]
to zero. However, the two pieces of code are used in completely different situations and cannot be replaced by each other:char a[100] = {0}
declares and initializes array variables. Before thata[]
didn’t exist.memset(a, 0, sizeof(a))
is to clear its contents aftera[]
has been declared previously.a[]
existed before this.Also,
memset
is a library function, not a capability of the language itself.char a[100] = {'0'} The content can be determined at compile time, while memset will not set the content to the specified value until runtime
One is to fill a with character 0 (0x30) and the other is to use 0. And C99 seems to automatically add '0' memset does not. Its meaning is to fill a certain area of an address with the specified content
char a[]
The obtained a may be on the stack, or it may be a global variable, but it does existmemset does not cause allocation, a can be anywhere
a[100] = {0}; can be regarded as syntactic sugar to quickly initialize variable memory for easy coding. It is only executed once when entering the scope. Of course, the scope can be executed again when entering the scope repeatedly.
Memset is a general function for setting memory and can be called at any time.
char a[100] = {0} is statically initialized to 0, and the corresponding memory is 0 before the program runs
memset() is dynamically initialized to 0, and the corresponding memory is cleared when the program runs