简体   繁体   中英

Character array without a null terminator in C

Sometimes I am using sequences of characters (strings) except the null terminator is not needed or wanted, for example if I am using memcpy() and the length is already known. A such, I prefer to omit the null terminator. A cumbersome way to do this would be declaring an array:

char no_term[5] = {'h', 'e', 'l', 'l', 'o'};

However, I would prefer to use quoted strings, as these are much more efficient to program with. However quoted strings automatically include a null terminator at the end. But would specifying the array size to exclude the null terminator invoke undefined behavior ? Is the following valid C , as long as I do not use these where a null terminated string is required (eg, passing them to strlen() )?

char no_term[5] = "hello";
char no_term_array[3][3] = {"foo", "bar", "baz"};

According to §6.7.9 ¶14 of the ISO C11 standard , arrays of character type may be initialized from a string literal, even if there is no room for the terminating null character.

So yes, your posted code is valid and will not invoke undefined behavior.

Note however that this is only legal in C, not C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM