c++ - char a[100] = {'\0'}与memset(a, 0, sizeof(a))有什么区别?
天蓬老师
天蓬老师 2017-04-17 15:24:09
0
7
1415

如题所 char a[100] = {'0'} 与 memset(a, 0, sizeof(a)) 什么区别?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(7)
大家讲道理
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;
大家讲道理

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.

巴扎黑

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 exist

memset does not cause allocation, a can be anywhere

Peter_Zhu

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.

PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!