Suppose I have the following c char arrays:
char okaysize4[5] = "four"; // line 5
char toosmall4[4] = "four"; // line 6
char toosmall3[3] = "four"; // line 7
When I compile with gcc 4.4.7, I get the following error:
array.c:7: warning: initializer-string for array of chars is too long
This error is expected for line 7, as I am trying to stuff 5 chars ("four" + \0)
into a 3 element array.
Also no error is expected for line 5 as the 5 element array is big enough.
However I'm surprised there is no similar error for line 6. What ends up getting initialized in toosmall4
is an unterminated string, which can cause all sorts of trouble.
My understanding is that the c string literal "four"
should be five characters long, due to the null terminator. In fact sizeof("four")
is 5. So why does the compiler not give an error here?
Is there some way I can alter my declaration/definition/initialization so that an error is flagged in this case?