Why is max length of C string literal different from max char[]?

后端 未结 3 1696
面向向阳花
面向向阳花 2020-12-06 10:31

Clarification: Given that a string literal can be rewritten as a const char[] (see below), imposing a lower max length on literals than on

3条回答
  •  渐次进展
    2020-12-06 10:41

    Sorry about the late answer, but I'd like to illustrate the difference between the two cases (Richard J. Ross already pointed out that they're not equivalent.)

    Suppose you try this:

    const char __THE_LITERAL[] = { 'f', 'o', 'o', '\0' };
    const char* str = __THE_LITERAL;
    char *str_writable = (char *) str;  // Not so const anymore
    str_writable[0] = 'g';
    

    Now str contains "goo".

    But if you do this:

    const char* str = "foo";
    char *str_writable = (char *) str;
    str_writable[0] = 'g';
    

    Result: segfault! (on my platform, at least.)

    Here is the fundamental difference: In the first case you have an array which is initialized to "foo", but in the second case you have an actual string literal.

    On a side note,

    const char __THE_LITERAL[] = { 'f', 'o', 'o', '\0' };
    

    is exactly equivalent to

    const char __THE_LITERAL[] = "foo";
    

    Here the = acts as an array initializer rather than as assignment. This is very different from

    const char *str = "foo";
    

    where the address of the string literal is assigned to str.

提交回复
热议问题