C语言数组中未初始化元素的值 [英] Value of uninitialized elements in array of C language

查看:499
本文介绍了C语言数组中未初始化元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个元素的数组.但是我只想初始化其中的2个. 我将第三个元素留空.

I have an array of 3 elements. But I only want to initialize 2 of them. I let the third element blank.

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

打印结果为0.我在IAR和一些在线编译器上对其进行了测试.

The print result is 0. I tested it on IAR, and some online compiler.

第三个元素的值是否有C规则? 是否有任何编译器用0xFF填充第三个元素? (特别是交叉编译器)

Is there any C rule for the value of third element? Is there any compiler filling the third element by 0xFF ? (Especially cross compiler)

推荐答案

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

Yes, the C standard does define what happens in this case. So no, there should be no C standard compliant compiler that intialises with 0xFF in this case.

该标准的第6.7.9节说:

Section 6.7.9 of the standard says:

初始化

...

10 ...如果具有静态或线程存储持续时间的对象不是 显式初始化,然后:

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如果括号括起来的列表中的初始化程序少于那里 是集合中的元素或成员,或者 用于初始化大小已知的数组的字符串文字 是数组中的元素,聚合的其余部分应为 隐式初始化为与具有静态存储的对象相同 持续时间.

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语言数组中未初始化元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆