C语言数组中未初始化元素的取值

Value of uninitialized elements in array of C language

我有一个包含 3 个元素的数组。但我只想初始化其中的两个。 我让第三个元素空白。

unsigned char array[3] = {1,2,};
int main(){
  printf("%d",array[2]);
    return 0;
}

打印结果为0,我在IAR和一些在线编译器上测试过。

第三个元素的取值有没有C规则? 有没有编译器用 0xFF 填充第三个元素? (尤其是交叉编译器)

是的,C 标准确实定义了在这种情况下会发生什么。所以不,在这种情况下,不应该有使用 0xFF 初始化的符合 C 标准的编译器。

标准第 6.7.9 节说:

Initialisation

...

10 ...If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

...

21 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.

this post 看来,该语法会将逗号后的所有元素初始化为零。而且;程序数据段中所有未初始化的数据(换句话说,所有未初始化的全局变量)都自动设置为零,因此如果您要在该程序中寻找未定义的行为,则没有;它将始终为 0。

这可以通过下面的 gcc 扩展来实现 无符号字符数组[10] = {1,2,[2 ... 9] = 0xFF};