Do char arrays initialized this way have null terminators automatically added?

Viewed 89

Does a char array initialized like so:

char foo[] = {0x31, 0x32, 0x33}; //123

get a null terminator added to the end of it so the memory data at foo would look something like 0x31323300? Or does this simply write 0x313233 to memory? Also, is foo treated like a string literal by the compiler regardless of this method of initialization?

3 Answers

No, if you don't specify a size of the array and do not use a string-literal as initializer, the size and contents of the array will be exactly matching the initializers you have.

In your case the array foo will be exactly three char elements containing (in order) 0x31, 0x32 and 0x33.

If you use a string-literal as initializer, then the array will include the terminator. And if you specify a size larger than the number of initializers (like e.g. char foo[4] in your example with three initializers) then the remaining elements will be zero-initialized (which is equal to the string terminator).

Also note that even if you use a string-literal as initializer, but specify a size smaller than the initializer, the array will also not be terminated.

foo is just a plain old char array with three elements, and no null-terminator. The only place the compiler would "magically" add a null terminator is when you use a string literal, i.e., a string denoted by double quotes ("):

char* string = "I have a null terminator";

Does a char array initialized like so:

`char foo[] = {0x31, 0x32, 0x33}; //123 get a null terminator added to the end of it?

No, it will simply be an array of chars.

Also is foo treated like a string literal by the compiler regardless of this method of initialization?

No, foo is not treated like a string literal. See here.

Related