如何在没有空终止符的情况下初始化char数组?
char数组是网络消息的一部分,具有明确的长度,因此不需要空终止符。
The char array is a part of network message, which has well defined length, so the null terminator is not needed.
struct Cmd {
char cmd[4];
int arg;
}
struct Cmd cmd { "ABCD" , 0 }; // this would be buffer overflow
如何初始化此cmd成员char数组?而不使用 strncpy
?
How can I initialize this cmd member char array? without using functions like strncpy
?
char
数组的大小与初始化程序中的字符数相同。因此 cmd
将没有空终止符。
Terminating null character is ignored if the size of the char
array is the same as the number of characters in the initializer. So cmd
will not have the null terminator.
C11标准(n1570)中的相关部分是 6.7.9 / 14 :
The relevant section in the C11 standard (n1570) is 6.7.9/14:
字符类型的数组可以由字符串文字或UTF-8字符串文字初始化,并可选地用大括号括起来。字符串文字的连续字节(包括终止空字符,如果有空间 ,或者数组的大小未知),将初始化数组的元素。
An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
语句:
struct Cmd cmd { "ABCD" , 0 };
应为:
struct Cmd cmd = { "ABCD" , 0 };