How to initialize all members of an array to the same value?

后端 未结 23 1808
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  情歌与酒
    2020-11-21 05:23

    If you want to ensure that every member of the array is explicitly initialized, just omit the dimension from the declaration:

    int myArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    

    The compiler will deduce the dimension from the initializer list. Unfortunately, for multidimensional arrays only the outermost dimension may be omitted:

    int myPoints[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
    

    is OK, but

    int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
    

    is not.

提交回复
热议问题