简体   繁体   English

是否在字符串结束后使用零/ null初始化char数组,此时还有剩余空间?

[英]Is a char array initialized with zeros/null after string end, when there's still space left?

Consider the following char array: 考虑以下char数组:

char str[128] = "abcd";

Are all the remaining uninitialized chars in the rest of the array (from str[4] to str[127] ) zero/null filled? 是否所有剩余的未初始化的字符在数组的其余部分(从str[4]str[127] )零/ null填充?

Yes, if there are fewer elements explicitly given in an initialiser than the aggregate contains, then the remaining elements are initialised as if the aggregate had static storage duration. 是的,如果初始化程序中明确给出的元素少于聚合所包含的元素,则初始化其余元素,就好像聚合具有静态存储持续时间一样。 For integer types (and char is one) that means with 0s. 对于整数类型(和char是一个),表示0。 The relevant section of the standard is 6.7.9 (21): 该标准的相关部分是6.7.9(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. 如果括号括起的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符数少于数组中的元素,则聚合的其余部分应为隐式初始化与具有静态存储持续时间的对象相同。

String literals as initialisers for char arrays are equivalent to brace-encloded initialisers in that respect. 字符串文字作为char数组的初始化者在这方面等同于大括号包含的初始化者。

Yes, the string literal initializer is identical to the following initializer: 是的,字符串文字初始值设定项与以下初始化程序相同:

char str[128] = { 'a', 'b', 'c', 'd', 0 };

Missing array elements are zero-initialized, hence the remainder of the array is all zeros. 缺少的数组元素是零初始化的,因此数组的其余部分全为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从字符串文字初始化char数组时会发生什么? - What happens when a char array gets initialized from a string literal? 为什么写入用字符串文字初始化的“char *s”而不是“char s[]”时会出现分段错误? - Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"? 如何在中间包含零的c中查找char数组的实际结尾 - how to find actual end of char array in c containing zeros in the middle 初始化固定大小的char数组而没有足够的空终止符空间时,没有编译器错误 - No compiler error when fixed size char array is initialized without enough room for null terminator 将char数组初始化为'\\ 0'时会发生什么? - What happens when a char array is initialized to '\0'? 是否在字符串末尾附加了两次空字符 - Is null char appended twice at the end of string 定义一个字符串,在结尾处没有空终止char(\\ 0) - Defining a string with no null terminating char(\0) at the end 为什么 char 数组必须以空字符结尾? - Why must a char array end with a null character? scanf在C之后使用\\ 0和一串零捕获char类型的字符串 - scanf catches char type string with \0 and bunch of zeros after in C 如何将空格字符添加到字符串/字符数组? - How do I add space char to string/char array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM