C 字符数组初始化 [英] C char array initialization
问题描述
我不确定通过以下方式初始化后char数组中会有什么.
I'm not sure what will be in the char array after initialization in the following ways.
1.char buf[10] = "";
2. char buf[10] = " ";
3. char buf[10] = "a";
对于情况 2,我认为 buf[0]
应该是 ' '
,buf[1]
应该是 '\0'
,从 buf[2]
到 buf[9]
将是随机内容.对于情况 3,我认为 buf[0]
应该是 'a'
,buf[1]
应该是 '\0',并且从buf[2]
到 buf[9]
将是随机内容.
For case 2, I think buf[0]
should be ' '
, buf[1]
should be '\0'
, and from buf[2]
to buf[9]
will be random content. For case 3, I think buf[0]
should be 'a'
, buf[1]
should be '\0', and from buf[2]
to buf[9]
will be random content.
正确吗?
对于情况 1,buf
中会有什么?buf[0] == '\0'
并且从 buf[1]
到 buf[9]
会是随机内容吗?
And for the case 1, what will be in the buf
? buf[0] == '\0'
and from buf[1]
to buf[9]
will be random content?
推荐答案
这不是初始化数组的方式,而是用于:
This is not how you initialize an array, but for:
第一个声明:
The first declaration:
char buf[10] = "";
相当于
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
第二个声明:
The second declaration:
char buf[10] = " ";
相当于
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
第三个声明:
The third declaration:
char buf[10] = "a";
相当于
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
如您所见,没有随机内容:如果初始化器较少,则数组的剩余部分使用 0
进行初始化.即使在函数内部声明数组也是如此.
As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0
. This the case even if the array is declared inside a function.
这篇关于C 字符数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!