如下代码,输出结果是什么?
#include <stdio.h>
int main()
{
int arr[10] = {10};
for(int i = 0;i < 10;i++)
printf("%d\n",arr[i]);
return 0;
}
输出结果:
10
0
0
0
0
0
0
0
0
0
本来以为应该全部输出的是10。
看到介绍:https://en.cppreference.com/w/c/language/array_initialization
文中有几个例子,引以为戒:
int x[] = {1,2,3}; // x has type int[3] and holds 1,2,3
int y[5] = {1,2,3}; // y has type int[5] and holds 1,2,3,0,0
int z[4] = {1}; // z has type int[4] and holds 1,0,0,0
int w[3] = {0}; // w has type int[3] and holds all zeroes
只有{0}时才全部初始化0,其余初始化是根据给定元素个数。