简体   繁体   中英

2D Array initialization of columns vs rows

If I have an array of 3 rows and 5 columns like this:

int arr[3][5]={0};

Now I want to input some numbers so I do like this:

int arr[3][5] ={10,8,9}

and now the array is set like this:

 10  8  9  0  0
  0  0  0  0  0
  0  0  0  0  0

But what I want is that actually the first column elements in the array are set like this:

10  0  0  0  0
8   0  0  0  0
9   0  0  0  0

How I can swap or change the array order to be like this?

You want this:

int arr[3][5] ={{10},{8},{9}};

This initializes each of the three first dimension arrays, and each of those explicitly initialize only the first element, causing the rest to be set to 0.

Breaking down the above initialization, arr is an array of size 3, where each element is an array of int of size 5. So {10} initializes the first of these 3 array elements, {8} initializes the second, and {9} initializes the third. And because each of these only initializes the first of the 5 elements of each subarray, the rest are initialized to 0.

From section 6.7.9 of the C standard :

19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject; all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

Why not write

int arr[3][5] = { {10, 0, 0, 0, 0},
                  {8, 0, 0, 0, 0},
                  {9, 0, 0, 0, 0 }};

ie Initialise every element in the array

使用指定的初始化器:

int test[3][5] = { [0][0] = 10 , [1][0] = 8 , [2][0] = 9 } ;

How i can swap or change the array order to be like this?

In C, not at all. That's not a language feature of C.

You'd have to use a for loop or something similar to iterate through the rows, rather than the columns, or use an array of one-element array initializers.

My suspicion is that you might actually want to look at some matrix libraries that make handling of mathematical structures easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM