How to initialize a char array without the null terminator?

[亡魂溺海] 提交于 2020-07-20 10:52:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!