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

后端 未结 4 1277
执念已碎
执念已碎 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:12

    If it's an auto variable, it will be filled with junk unless you explicitly initialize it, so there is no default value. arr[0] will likely contain a seemingly random value until explicitly changed to contain something else.

    Of course, if you initialized the array (meaning that you filled the array with initial values explicitly using something like memset() or a for loop or a function call or whatever other means), you'll get exactly what you expect: the value with which you initialized it.

    Do note though the difference between declaration and initialization.

    void f(void) {
        int x;  // (1)
        x = 10; // (2)
    }
    

    At (1), you're declaring an auto integer variable. It has an undefined value right now (junk). At (2), you're initializing the variable. It now has the value of 10.

    Of course, declaration and initialization can both be done at once:

    void f(void) {
        int x = 10;
    }
    

    The same thing is true for arrays:

    void f(void) {
        int x[2];  // x contains 2 junk values, so x[0] == junk
        x[0] = 1;  // x contains { 1, junk },   so x[0] == 1
        x[1] = 2;  // x contains { 1, 2 },      so x[0] == 1
    }
    

    or, to declare and initialize it:

    void f(void) {
        int x[2] = { 1, 2 };
    }
    

提交回复
热议问题