我可以假设二维数组像这样正确初始化吗?

发布于 2024-08-21 22:40:20 字数 160 浏览 7 评论 0原文

当我像这样声明一个二维数组时:

char myArray[20][30] = {"ABC", "Is Easy As One Two Three"};

我可以假设该数组中的所有其他字符现在都设置为 \000 吗?

When I declare a two-dimensional array like this:

char myArray[20][30] = {"ABC", "Is Easy As One Two Three"};

Can I assume that all other chars in this array are now set to \000?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

动次打次papapa 2024-08-28 22:40:20

在 C 中,对象永远不会部分初始化 - 如果您使用了初始化程序,则保证整个对象被初始化(在这种情况下,“对象”是由 20 个数组组成的整个数组,每个数组包含 30 个字符)。任何未显式初始化的成员都会递归地初始化为零(对于算术类型)或 NULL(对于指针类型)。

因此,在这种情况下,答案是肯定的 - 所有未由初始化器显式指定值的 char 都保证为 0。

这在 C99 标准的第 6.7.8 节“初始化”中进行了描述。相关段落是:

21 如果初始化器较少
一个用大括号括起来的列表
集合的元素或成员,
字符串中的字符或更少
用于初始化数组的文字
已知大小比其中元素的大小
数组的剩余部分
应初始化聚合
与以下对象隐式相同
具有静态存储期限。

10 如果一个对象具有自动
存储期限未初始化
明确地,它的值是
不定。如果一个对象有
静态存储持续时间不是
显式初始化,然后:

——如果是的话
具有指针类型,它被初始化为
空指针;

——如果有算术
类型,它被初始化为(正
或无符号)零;

——如果它是一个
聚合,每个成员都被初始化
(递归地)根据这些
规则;

——如果是并集,则第一个
命名成员已初始化
(递归地)根据这些
规则。

Objects are never partially initialised in C - if you have used an initialiser, then the entire object is guaranteed to be initialised (in this case, the "object" is the whole array of 20 arrays of 30 chars each). Any members not explicitly initialised are recursively initialised to zero (for arithmetic types), or NULL (for pointer types).

So the answer, in this case, is yes - all the chars not explicitly given values by the initialiser are guaranteed to be 0.

This is described in the C99 standard in section 6.7.8, Initialisation. The relevant paragraphs are:

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.

and

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

— if it is a union, the first
named member is initialized
(recursively) according to these
rules.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文