What is the default value of members of a char array in C?

后端 未结 4 1254
执念已碎
执念已碎 2021-01-02 19:14

Say I create a char array, and I assume the char array is empty. If I check the value of the first element in the array (arr[0]), what would be the

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 20:02

    It depends on where and how the array is declared.

    If the array is declared at file scope (outside of any function), or is declared static, and does not have an explicit initializer, then the contents of the array will be initialized to 0.

    If the array is declared at block scope (within a function or block) and is not declared static, and does not have an explicit initializer, then the contents of the array are indeterminate (essentially, garbage values, some of which may be trap representations).

    If the array has been explicitly initialized, then it contains whatever was in the initializer.

    EDIT

    In response to the comments below, note that you shouldn't rely on implicit initialization for block-scope variables. If you need a block-scope array to be zeroed out on creation, use an initializer:

    char foo[N] = {0};
    

    When there are fewer elements in the initializer than there are in the array, elements in the array corresponding to elements in the initializer will be set to the value specified; all remaining entries will be implicitly initialized as if they were declared static.

    In the example above, this means that the first element of foo is explicitly set to 0, while all the remaining elements are implicitly set to 0.

提交回复
热议问题