[英]Why do we put the null terminator in brace enclosed char array initialization
I noticed that in many books and online tutorials when C strings are initialized using brace enclosed lists, it is done like this: 我注意到,在许多书籍和在线教程中,使用括号括起来的列表初始化C字符串时,都是这样完成的:
char string[100] = {'t', 'e', 's', 't', '\0' };
Shouldn't all unspecified values automatically be set to 0 (aka '\\0'
)? 是否所有未指定的值都不应该自动设置为0(又名
'\\0'
)?
I tested this on multiple versions of GCC and MSVC, all values are indeed set to zero, but I'm wondering if there's a specific reason for explicitly writing the null terminator when initializing. 我在GCC和MSVC的多个版本上进行了测试,所有值确实都设置为零,但是我想知道是否有特定的原因在初始化时明确编写空终止符。
You're right (see "Initialization from brace-enclosed lists" here ). 你是对的(请参阅“从括号括起来的初始化列表” 在这里 )。 But it's a good practice because this would also compile without complaints:
但这是一个好习惯,因为这样也可以毫无抱怨地进行编译:
char string[4] = {'t', 'e', 's', 't'};
but wouldn't null-terminate anything, which would lead to errors whenever you would use that as a string. 但不会以null终止任何东西,每当您将其用作字符串时,都会导致错误。 If you say
如果你说
char string[4] = {'t', 'e', 's', 't', '\0'};
the compiler will know it's an error because the '\\0'
won't fit. 编译器会知道这是一个错误,因为
'\\0'
不适合。
Note that it's superior even to 请注意,它甚至比
char string[100] = "test";
for the same reason: 出于同样的原因:
char string[4] = "test";
does the same as the first example, not the second! 与第一个示例相同,而不是第二个!
It's to prevent silly mistakes. 这是为了防止愚蠢的错误。 The first null character is required if the characters are to be interpreted as a string.
如果要将字符解释为字符串,则需要第一个空字符。
char string[4] = {'t', 'e', 's', 't'};
will happily compile, but will not be null-terminated. 将很高兴地进行编译,但不会以null结尾。
char string[4] = {'t', 'e', 's', 't', '\0'};
will fail to compile, which is the point. 将无法编译,这就是重点。
By explicitly specifying the null character, the compiler will verify that the array is large enough for its intended purpose. 通过显式指定空字符,编译器将验证数组足够大以达到其预期目的。
Adding null terminator is absolutely unnecessary when you specify the size of your character array explicitly, and allocate more chars than is needed for the payload portion of your string. 当您明确指定字符数组的大小并分配比字符串的有效负载部分所需更多的字符时,绝对不需要添加空终止符。 In this situation the standard requires that the remaining chars be initialized with zeros.
在这种情况下,标准要求将剩余字符用零初始化。
The only time when it is necessary is when you want the size of a null-terminated array to be determined automatically by the compiler, ie 唯一必要的时间是希望由编译器自动确定以空值结尾的数组的大小,即
char string[] = {'t', 'e', 's', 't', '\0' };
// ^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.