I know that in C string assignment must go through
char string[4];
strcpy(string, "aaa");
but why and how does C allow
char string[] = "string";
?
Thanks in advance
I know that in C string assignment must go through
char string[4];
strcpy(string, "aaa");
but why and how does C allow
char string[] = "string";
?
Thanks in advance
You seem to have misunderstood something. According to gcc you are allowed to do:
char string[4] = "aaa";
The difference to char string[] = "aaa";
is only that the compiler infers the length of string
from it's initializer. There's nothing different to other types of arrays here - just the fact that you may use a string literal as an initializer instead of an array literal.
char string[] = "string";
Here, the right length of string
is automatically calculated by the compiler so that there's enough room for the string and the NUL character.
char string[4];
strcpy(string, "aaa");
Here strcpy
may access beyond the array bounds if the string is larger than the actual string
capacity.