字符串文字是否算作部分初始化程序并进行零初始化? [英] Does a string literal count as a partial initializer and zero-initialize?

查看:14
本文介绍了字符串文字是否算作部分初始化程序并进行零初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,您可以部分初始化结构或数组,结果是初始化程序中未提及的成员/元素被零初始化.(C99 第 6.7.8.19 节).例如:-

In C, you can partially initialize a struct or array, with the result that the members/elements that aren't mentioned in the initializer are zero-initialized. (C99 section 6.7.8.19). For example:-

int a[4] = {1, 2};
// a[0] == 1
// a[1] == 2
// a[2] == 0
// a[3] == 0

您还可以使用字符串文字(C99 第 6.7.8.14 节)初始化字符类型的数组",以及连续字符......初始化数组的元素".例如:-

You can also initialize "an array of character type" with a string literal (C99 section 6.7.8.14), and "successive characters ... initialize the elements of the array". For example:-

char b[4] = "abc";
// b[0] == 'a'
// b[1] == 'b'
// b[2] == 'c'
// b[3] == ''

一切都非常简单.但是,如果您明确给出数组的长度,但使用的文字太短而无法填充数组,会发生什么?剩余的字符是零初始化的,还是有未定义的值?

All pretty straightforward. But what happens if you explicitly give the length of the array, but use a literal that's too short to fill the array? Are the remaining characters zero-initialized, or do they have undefined values?

char c[4] = "a";
// c[0] == 'a'
// c[1] == ''
// c[2] == ?
// c[3] == ?

将其视为部分初始化程序是有意义的,它会使 char c[4] = "a" 的行为与 char c[4] = {'a'},它会产生有用的副作用,让您使用 char d[N] = "" 简洁地对整个字符数组进行零初始化,但我完全不清楚这就是规范所要求的.

Treating it as a partial initializer would make sense, it would make char c[4] = "a" behave exactly like char c[4] = {'a'}, and it would have the useful side-effect of letting you zero-initialize a whole character array concisely with char d[N] = "", but it's not at all clear to me that that's what the spec requires.

推荐答案

 char c[4] = "a";

数组的所有剩余元素将设置为 0.也就是说,不仅有c[1],还有c[2]c[3].

All the remaining elements of the array will be set to 0. That is, not only c[1] but also c[2] and c[3].

请注意,这不取决于 c 的存储持续时间,即.即,即使 c 具有自动存储持续时间,其余元素也将设置为 0.

Note that this does not depend on the storage duration of c, i. e., even if c has automatic storage duration the remaining elements will be set to 0.

来自 C 标准(重点是我的):

From the C Standard (emphasis mine):

(C99, 6.7.8p21) 如果大括号括起来的列表中的初始化器少于聚合的元素或成员,或字符串文字中的更少字符用于初始化已知大小的数组比数组中的元素多,聚合的其余部分应隐式初始化,与具有静态存储持续时间的对象相同."

(C99, 6.7.8p21) "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."

这篇关于字符串文字是否算作部分初始化程序并进行零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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