How to initialize N dimensional arrays in C without using loop

后端 未结 4 862
夕颜
夕颜 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:26

    In your case, you could do with

    int a[3][3] = {{}, {}, {1,1,1}}; 
    

    Notice that the empty curly braces will be automatically filled with 0.

    Now, if you want

    0 0 0
    0 0 0
    1 0 0
    

    you could do it with:

    int a[3][3] = {{}, {}, {1,}};
    

    For details, please look at How to initialize all members of an array to the same value? (this is for unidimensional array, but it will help you understand what is written above.)

    Also, http://c-faq.com/~scs/cclass/notes/sx4aa.html is a good resource for array initialization.

    0 讨论(0)
  • 2021-01-25 07:30
    int matrix[3][3] = {
        { 0, 0, 0 },
        { 0, 0, 0 },
        { 1, 1, 1 }
    };
    

    Or, the more compact:

    int matrix[3][3] = {
        [2] = { 1, 1, 1 }
    };
    

    The solution generalizes for N so long as N is fixed. If N is large, you can use mouviciel's answer to this question.

    0 讨论(0)
  • 2021-01-25 07:33
    matrix[0][2] = matrix[0][1] = matrix[0][0] =
    matrix[1][2] = matrix[1][1] = matrix[1][0] = 0;
    matrix[2][2] = matrix[2][1] = matrix[2][0] = 1;
    

    or

    #include <string.h>
    ...
    memset(matrix, 0, sizeof(matrix));
    matrix[2][2] = matrix[2][1] = matrix[2][0] = 1;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题