定义的字符串是否设置为所有 NULL?
Are defined strings set to all NULLs?
我可以发誓我读到一个已定义但未初始化的字符串被设置为所有 NULL。也就是说,
char string[10];
由 10 个空字符组成,
char string[10] = "Kevin";
由字母 'K'、'e'、'v'、'i'、'n' 和五个空值组成。
这是真的吗:
- 总是?
- 有时,取决于编译器?
- 从来没有?
如果不存在初始化程序(如您的第一个示例),则数组的 all 元素将具有不确定的值。来自 this C11 Draft Standard:
6.7.9 Initialization
…
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
但是,如果您提供 any 类型的初始值设定项(如您的第二个示例中所示),则数组中任何未 显式 set 将被初始化为零。来自标准后面的几段:
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.
(注意一个char
的静态存储时长会被初始化为零。)
in other words, that char string[10]; consisted of 10 null characters,
这取决于位置和变量。
char here_yes[10]; // 10 '[=10=]' characters
int main() {
char here_no[10]; // 10 unknown garbage values
static char but_here_also_yes[10]; // also 10 '[=10=]' characters
}
and that char string[10] = "Kevin"; consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls. Is this true: Always?
是的。如果你部分初始化了一个字符串或一个变量,剩下的部分用'[=12=]'
或零填充。
char this_has_10_nulls[10] = "";
int main() {
char this_has_ab_followed_by_8_nulls[10] = { 'a', 'b' };
static char this_has_Kevin_followed_by_5_nulls[10] = "Kevin";
}
我可以发誓我读到一个已定义但未初始化的字符串被设置为所有 NULL。也就是说,
char string[10];
由 10 个空字符组成,
char string[10] = "Kevin";
由字母 'K'、'e'、'v'、'i'、'n' 和五个空值组成。
这是真的吗:
- 总是?
- 有时,取决于编译器?
- 从来没有?
如果不存在初始化程序(如您的第一个示例),则数组的 all 元素将具有不确定的值。来自 this C11 Draft Standard:
6.7.9 Initialization
…
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
但是,如果您提供 any 类型的初始值设定项(如您的第二个示例中所示),则数组中任何未 显式 set 将被初始化为零。来自标准后面的几段:
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.
(注意一个char
的静态存储时长会被初始化为零。)
in other words, that char string[10]; consisted of 10 null characters,
这取决于位置和变量。
char here_yes[10]; // 10 '[=10=]' characters
int main() {
char here_no[10]; // 10 unknown garbage values
static char but_here_also_yes[10]; // also 10 '[=10=]' characters
}
and that char string[10] = "Kevin"; consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls. Is this true: Always?
是的。如果你部分初始化了一个字符串或一个变量,剩下的部分用'[=12=]'
或零填充。
char this_has_10_nulls[10] = "";
int main() {
char this_has_ab_followed_by_8_nulls[10] = { 'a', 'b' };
static char this_has_Kevin_followed_by_5_nulls[10] = "Kevin";
}