Should statically-declared character arrays with a specified size be initialized with a literal in C?

前端 未结 1 642
孤独总比滥情好
孤独总比滥情好 2021-01-23 06:47

For example,

gcc compiles this ok...

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

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



        
相关标签:
1条回答
  • 2021-01-23 07:16

    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.

    0 讨论(0)
提交回复
热议问题