Search code examples
carrayscolumn-major-orderrow-major-order

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?


Solution

  • 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.