Initializing char Array with Smaller String Literal

后端 未结 4 2015
甜味超标
甜味超标 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.

    0 讨论(0)
  • 2021-01-04 09:51

    This is standard behavior. Every element of an array that is not explicitly initialized is initialized to a default value ('\0' for char), if any prefix of the array is initialized in the declaration. It also works for other types:

    int a[10] = {1};
    

    zeroes out a[1] through a[9].

    0 讨论(0)
  • 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};
    
    0 讨论(0)
  • 2021-01-04 10:00

    According to the standard, all indices beyond what is specified will be set to zero/null. More information in this SO post

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