Reputation: 177
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?
Upvotes: 2
Views: 122
Reputation: 409136
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).
If you use a string literal as initializer, but a size smaller than the string length (including the null-terminator) then the compiler will complain. You must have a size at least the same length as the string (including null-terminator).
Upvotes: 6
Reputation: 76
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.
Upvotes: 2
Reputation: 311038
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";
Upvotes: 3