Reputation: 728
I've been reading some code and I encountered the following:
int function(){
char str[4] = "ABC\0";
int number;
/* .... */
}
Normally, when you write a string literal to initialize a char array, the string should be null terminated implicitly right? What happens in this case? Does the compiler recognize the '\0' in the string literal and make that the null terminator? or does it overflow to the int number? Is there anything wrong with this form?
Upvotes: 3
Views: 11124
Reputation: 9680
The C99 standard §6.7.8.¶14 says
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character 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.
This means that the following statements are equivalent.
char str[4] = "ABC\0";
// equivalent to
char str[4] = "ABC";
// equivalent to
char sr[4] = {'A', 'B', 'C', '\0'};
So there's nothing wrong with the first statement above. As the standard explicitly states, only that many characters in the string literal are used for initializing the array as the size of the array. Note that the string literal "ABC\0"
actually contains five characters. '\0'
is just like any character, so it's fine.
However please note that there's a difference between
char str[4] = "ABC\0";
// equivalent to
char str[4] = {'A', 'B', 'C', '\0'};
char str[] = "ABC\0"; // sizeof(str) is 5
// equivalent to
char str[] = {'A', 'B', 'C', '\0', '\0'};
That's because the string literal "ABC\0"
contains 5
characters and all these characters are used in the initialization of str
when the size of the array str
is not specified. Contrary to this, when the size of str
is explicitly stated as 4
, then only the first 4
characters in the literal "ABC\0"
are used for its initialization as clearly mentioned in the above quoted para from the standard.
Upvotes: 7
Reputation: 122493
If the code is:
char str[3] = "ABC";
It's fine in C, but the character array str
is not a string because it's not null-terminated. See C FAQ: Is char a[3] = "abc"; legal? What does it mean? for detail.
In your example:
char str[4] = "ABC\0";
The last character of the array str
happens to be set to '\0'
, so it's fine and it's a string.
Upvotes: 6