How to initialize N dimensional arrays in C withou

2020-04-27 13:58发布

问题:

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 without using loops as shown below

0 0 0
0 0 0
1 1 1

I would also like a solution for N dimiensional array

回答1:

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.



回答2:

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;


回答3:

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.



回答4:

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.