If I write:
char arr[8] = "abc";
Is there any specification over what arr[4]
might be? I did some tests with
Clang and it seems that the remaining chars in the array are set to null.
Also, char arr[8] = "";
zeroes every byte. Not sure if this is a compiler
convenience, standard behavior, pure coincidence or I got it wrong.
void a()
{
char arr[8] = "abc"; /* breakpoint here, line 3 */
strcpy(arr, "1234567");
}
int main()
{
a();
a();
return 0;
}
Debugger transcript:
Breakpoint 1, a () at str.c:3 3 char arr[8] = "abc"; (gdb) s Current language: auto; currently minimal 4 strcpy(arr, "1234567"); (gdb) p arr $1 = "abc\000\000\000\000" (gdb) c Continuing. Breakpoint 1, a () at str.c:3 3 char arr[8] = "abc"; (gdb) p arr $2 = "1234567" (gdb) s 4 strcpy(arr, "1234567"); (gdb) p arr $3 = "abc\000\000\000\000"
It's standard behavior.
arr[3]
is initialized to 0 because the terminating 0 is part of the string literal.
All remaining elements are initialized to 0 too -- ISO/IEC 9899:1999, 6.7.8, 21:
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
And char
objects with static storage are initialized to 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With