Should statically-declared character arrays with a specified size be initialized with a literal in C?
For example,
gcc compiles this ok...
char s[7] = "abc"开发者_如何学Go;
But it gives the error "incompatible types in assignment" with...
char s[7];
s = "abc";
What is the difference?
The first one is an initialization; it means "declare an array of 7 char
on the stack, and fill the first 3 elements with 'a'
, 'b'
, 'c'
, and the remaining elements with '\0'
".
In the second one, you're not initializing the array to anything. You're then trying to assign to the array, which is never valid. Something like this would "work":
const char *s;
s = "abc";
But the meaning would be slightly different (s
is now a pointer, not an array). In most situations, the difference is minimal. But there are several important caveats, for instance you cannot modify the contents. Also, sizeof(s)
would given you the size of a pointer, whereas in your original code, it would have given you 7 (the size of the array).
Recommended reading is this: http://c-faq.com/charstring/index.html.
精彩评论