char 数组的大小大于传递给初始化它的元素数
Size of char array is bigger than number of elements passed to initialize it
对于int或double类型的数组,如果数组的大小大于数组初始化时提供的元素个数(如列表),则数组中其余元素默认为0对吗?
当我用少于我提供的大小的元素初始化字符数组时会发生什么?喜欢
char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
其余元素是否赋值?或者它只是内存中的垃圾?
这个声明
char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
相当于这个声明
char ch[10] = { "hello" };
反过来等同于以下声明
char ch[10] = "hello";
所有这些声明等同于以下声明
char ch[10] = { 'h', 'e', 'l', 'l', 'o', '[=13=]', '[=13=]', '[=13=]', '[=13=]', '[=13=]', };
即数组中没有显式初始化器的元素被隐式零初始化。
来自C标准(6.7.9初始化)
10 If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate. If an object that has static
or thread storage duration is not initialized explicitly, then:
...
— if it has arithmetic type, it is initialized to (positive or
unsigned) zero;
和
19 The initialization shall occur in initializer list order, each
initializer provided for a particular subobject overriding any
previously listed initializer for the same subobject;151) all
subobjects that are not initialized explicitly shall be initialized
implicitly the same as objects that have static storage duration.
对于int或double类型的数组,如果数组的大小大于数组初始化时提供的元素个数(如列表),则数组中其余元素默认为0对吗?
当我用少于我提供的大小的元素初始化字符数组时会发生什么?喜欢
char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
其余元素是否赋值?或者它只是内存中的垃圾?
这个声明
char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
相当于这个声明
char ch[10] = { "hello" };
反过来等同于以下声明
char ch[10] = "hello";
所有这些声明等同于以下声明
char ch[10] = { 'h', 'e', 'l', 'l', 'o', '[=13=]', '[=13=]', '[=13=]', '[=13=]', '[=13=]', };
即数组中没有显式初始化器的元素被隐式零初始化。
来自C标准(6.7.9初始化)
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
...
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
和
19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.