Initialization of C array at time other than declaration?

前端 未结 5 491
[愿得一人]
[愿得一人] 2020-12-17 10:40

I know in C that I can do the following.

int test[5] = {1, 2, 3, 4, 5};

Now this is only legal when declaring the array. However I was wond

5条回答
  •  渐次进展
    2020-12-17 10:59

    The point is that using int array[]={ } is declaring and initializing the object that you have created.

    You can actually assign values to an array after it has been declared:

    int array[5];
    array[0] = 1, array[1] = 2, ...
    

    What you were doing was assigning several values to one single array entry:

    array[5] = {1,2,3,4,5}; // array[5] can only contain one value
    

    This would be legal instead:

    array[5] = 6;
    

    Hope this makes sense. Just a question of syntax.

提交回复
热议问题