数组中未初始化的元素的值是什么? [英] What will be the value of un-initialized element in the array?

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

问题描述

我有以下代码

int t[] = {
        [1] = 45,
        [2] = 33
    };

在这种情况下,t[0]的值是什么?它会包含垃圾吗?

What will be the value of t[0] in this case? It will contains garbage?

推荐答案

其他值将被初始化;根据C11标准,§6.7.9初始化,¶19和¶21:

The other value(s) will be initialized; from C11 standard, §6.7.9 Initialization, ¶19 and ¶21:

初始化应以初始化列表的顺序发生,为特定子对象提供的每个初始化都将覆盖先前为同一子对象列出的任何初始值; 151)所有未明确初始化的子对象应进行隐式初始化.与具有静态存储持续时间的对象相同.

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

151)子对象的任何初始化器都将被覆盖,因此不用于初始化该子对象.

如果用大括号括起来的列表中的初始化程序少于集合中的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符少于该数组中的元素,则其余聚合应与具有静态存储持续时间的对象隐式初始化.

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.

和具有静态存储持续时间的未初始化int被隐式初始化为零;同一部分,¶10:

And uninitialized int with static storage duration are implicity initialized to zero; same section, ¶10:

如果未自动初始化具有自动存储期限的对象,则其值不确定.如果未明确初始化具有静态或线程存储持续时间的对象,则:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 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 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;

在C89和C99中,行为相同.

The behavior is the same in C89 and C99.

这篇关于数组中未初始化的元素的值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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