Initializing char Array with Smaller String Literal

后端 未结 4 2038
甜味超标
甜味超标 2021-01-04 09:29

If I write:

char arr[8] = \"abc\";

Is there any specification over what arr[4] might be? I did some tests with Clang and it se

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 09:50

    It's standard behavior.

    arr[3] is initialized to 0 because the terminating 0 is part of the string literal.

    All remaining elements are initialized to 0 too -- ISO/IEC 9899:1999, 6.7.8, 21:

    If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

    And char objects with static storage are initialized to 0.

提交回复
热议问题