How to initialize N dimensional arrays in C without using loop

后端 未结 4 868
夕颜
夕颜 2021-01-25 07:00

I want to initalize a 3 x 3 matrix with first two rows as 0\'s and last row as 1\'s. I have declared a 2D array int matrix[3][3]

I want to initialize it wit

4条回答
  •  余生分开走
    2021-01-25 07:46

    For an constant integer expression N (say a macro or an enum constant) you'd have to "unroll" the initializer. There are macro tricks to do this when N expands to a decimal constant, but they are a bit involved. P99 provides such macros, with that you could write

    #define N 23
    
    int matrix[N][N] = {
        [N-1] = P99_DUPL(N, 1),
    };
    

    This lets you easily change N if you need it without having to touch anything else in your code for the update.

提交回复
热议问题