...
This noncompliant code example initializes an array of characters using a string literal that defines one more character (counting the terminating '\0'
) than the array can hold.:
Code Block | ||||
---|---|---|---|---|
| ||||
const char s[3] = "abc"; |
...
This approach is preferred because the size of the array can always be derived even if the size of the string literal changes.
Exceptions
STR36-EX0EX1: If the intention is to create a character array and not a null-terminated byte string, initializing to fit exactly without a null byte is allowed but not recommended. The preferred approach to create an array containing just the three characters 'a'
, 'b'
, and 'c'
, for example, is to declare each character literal as a separate element as follows:
...