gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:48:34 25 4
gpt4 key购买 nike

我有一个包含 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.

关于c - C语言数组中未初始化元素的取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com