I read this question and its answer in a book. But I didn\'t understand the book\'s justification.
Will the following code compile?
Your book must be pretty old, because gcc puts out a warning even without -Wall
turned on:
$ gcc c.c c.c: In function `main': c.c:6: warning: initializer-string for array of chars is too long
If we slightly update the program:
#include
int main(int argc, char **argv)
{
char str[5] = "1234567890";
printf("%s\n", str);
return 0;
}
We can see that gcc seems to truncate the string to the length you've specified; I'm assuming that there happens to be a '\0'
where str[6]
would be, because otherwise we should see garbage after the 5; but maybe gcc implicitly makes str
an array of length 6 and automatically sticks the '\0'
in there - I'm not sure.
$ gcc c.c && ./a.exe c.c: In function `main': c.c:6: warning: initializer-string for array of chars is too long 12345