Initializing char Array with Smaller String Literal

后端 未结 4 2037
甜味超标
甜味超标 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 10:00

    char arr[8] = "abc";
    

    is completely equivalent to

    char arr[8] = {'a', 'b', 'c', '\0'};
    

    ISO C 6.7.8 §21 states that

    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.

    In plain English this means that all values at the end of your array will be set to 0. So the standard guarantees that your code is equivalent to:

    char arr[8] = {'a', 'b', 'c', '\0', 0, 0, 0, 0};
    

    Now of course, '\0' happens to be value zero as well.

    This rule is universal to all arrays and not just to strings. Also, the same applies when initializing a struct but only explicitly setting a few of its members (6.7.8 §18).


    This is why you can write code like

    char arr[8] = "";
    

    In this example, the first element of the array is initialized explicity to '\0', and the rest of the items implicitly to zero. The compiler translates this to

    char arr[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    

提交回复
热议问题