Should statically-declared character arrays with a

2020-04-17 05:09发布

For example,

gcc compiles this ok...

char s[7] = "abc";

But it gives the error "incompatible types in assignment" with...

char s[7];
s = "abc";

What is the difference?

1条回答
一夜七次
2楼-- · 2020-04-17 05:54

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.

查看更多
登录 后发表回答