问题
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
How can I initialize this cmd member char array? without using functions like strncpy
?
回答1:
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.
The relevant section in the C11 standard (n1570) is 6.7.9/14:
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.
And the statement:
struct Cmd cmd { "ABCD" , 0 };
should be:
struct Cmd cmd = { "ABCD" , 0 };
来源:https://stackoverflow.com/questions/56105682/how-to-initialize-a-char-array-without-the-null-terminator