c中数组的所有元素如何初始化为零,第一个元素如何初始化为1
How all the elements of array initialize to zero and first element to 1 in c
这是程序,当声明为 int arr[10]={1}
时,数组自动初始化为零,第一个元素初始化为 1
#include<stdio.h>
int main()
{
int i;
int arr[10]={1};
for(i=0;i<10;i++)
{
printf("\n%d",arr[i]);
}
return 0;
}
除了第一个元素之外,数组元素如何初始化为零?
数组元素根据 C 标准中指定的带有初始化列表的聚合类型的初始化规则进行初始化。
它提到,如果大括号列表中提供的初始化器数量少于聚合类型中元素的数量,则聚合中的 remaining 个元素type 将用值初始化,就好像它们具有 static
存储持续时间一样,即值 0.
引用C11
,章节§6.7.9,初始化(强调我的)
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
以及关于具有 static
存储持续时间的变量的初始化,
[..] 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;
- [...]
所以,非常正确,在你的情况下
int arr[10]={1};
arr[0]
的值是 1
,arr[1]
到 arr[9]
都设置为 0
。
这是程序,当声明为 int arr[10]={1}
时,数组自动初始化为零,第一个元素初始化为 1#include<stdio.h>
int main()
{
int i;
int arr[10]={1};
for(i=0;i<10;i++)
{
printf("\n%d",arr[i]);
}
return 0;
}
除了第一个元素之外,数组元素如何初始化为零?
数组元素根据 C 标准中指定的带有初始化列表的聚合类型的初始化规则进行初始化。
它提到,如果大括号列表中提供的初始化器数量少于聚合类型中元素的数量,则聚合中的 remaining 个元素type 将用值初始化,就好像它们具有 static
存储持续时间一样,即值 0.
引用C11
,章节§6.7.9,初始化(强调我的)
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
以及关于具有 static
存储持续时间的变量的初始化,
[..] 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;
- [...]
所以,非常正确,在你的情况下
int arr[10]={1};
arr[0]
的值是 1
,arr[1]
到 arr[9]
都设置为 0
。