Confusion about array initialization in C

后端 未结 7 1311
不知归路
不知归路 2020-12-12 18:13

In C language, if initialize an array like this:

int a[5] = {1,2};

then all the elements of the array that are not initialized explicitly w

7条回答
  •  暖寄归人
    2020-12-12 18:14

    I try to give a short and simple answer for the puzzle: int a[5] = { a[2] = 1 };

    1. First a[2] = 1 is set. That means the array says: 0 0 1 0 0
    2. But behold, given that you did it in the { } brackets, which are used to initialize the array in order, it takes the first value (which is 1) and sets that to a[0]. It is as if int a[5] = { a[2] }; would remain, where we already got a[2] = 1. The resulting array is now: 1 0 1 0 0

    Another example: int a[6] = { a[3] = 1, a[4] = 2, a[5] = 3 }; - Even though the order is somewhat arbitrary, assuming it goes from left to right, it would go in these 6 steps:

    0 0 0 1 0 0
    1 0 0 1 0 0
    1 0 0 1 2 0
    1 2 0 1 2 0
    1 2 0 1 2 3
    1 2 3 1 2 3
    

提交回复
热议问题