如题所 char a[100] = {'0'} 与 memset(a, 0, sizeof(a)) 什么区别?
大家讲道理2017-04-17 15:26:09
char a[100] = {'0'};
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
char a[100] = {'杠0'}; // 大雾
The first element is initialized with 'bar 0', and subsequent elements are still value-initialized.
and
memset(a, 0, sizeof(a))
is equivalent to
for (int i=0; i<sizeof(a); ++i)
((char *)a)[i] = 0;
大家讲道理2017-04-17 15:26:09
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.
巴扎黑2017-04-17 15:26:09
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
高洛峰2017-04-17 15:26:09
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
PHP中文网2017-04-17 15:26:09
char a[]
The obtained a may be on the stack, or it may be a global variable, but it does exist
memset does not cause allocation, a can be anywhere
天蓬老师2017-04-17 15:26:09
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.
PHPz2017-04-17 15:26:09
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