printing a 2D array :warning: excess elements in array initializer

329 views Asked by At

I'm trying to print 8 rows and 5 columns in my output, but my code is throwing errors saying:

warning: excess elements in array initializer. 

This is my code:

#include <stdio.h>
  
void main()
{
   int rows,columns;
   int array[8][5] =
   {
    { 11, 12, 13, 14, 15 }, { 21, 22, 23, 24, 25 },
    { 31, 32, 33, 34, 35 }, { 41, 42, 43, 44, 45 },
    { 51, 52, 53, 54, 55 }, { 61, 62, 63, 64, 65 },
    { 71, 72, 73, 74, 75 }, { 81, 82, 83, 84, 85 },
   };
   
   for(columns=0;columns<=4;columns++)
   {
       for(rows=0;rows<=7;rows++)
       {  
            printf("%d",array[rows][columns]);
       }
       printf("\n");
   }
}

Can anyone please help me fix this code snippet?

1

There are 1 answers

8
Jonathan Leffler On

You have:

int array[5][8]= {{11,12,13,14,15},{21,22,23,24,25},{31,32,33,34,35},{41,42,43,44,45},{51,52,53,54,55},{61,62,63,64,65},{71,72,73,74,75},{81,82,83,84,85}};

That declares an array of five sub-arrays with eight elements in each sub-array, but you try to initialize it with eight sub-arrays (with five elements in each), and that is why you get the error message about "excess elements". If there were only five sub-arrays with five elements in each, the last three elements in each sub-array would be zeroed.

Fortran does this differently from C. See Wikipedia on Row-major vs Column-major order.

You need to either use int array[8][5] = { … }; or you need to regroup your initializers into five groups of eight, not eight groups of five.

int array[8][5] =
{
    { 11, 12, 13, 14, 15 }, { 21, 22, 23, 24, 25 },
    { 31, 32, 33, 34, 35 }, { 41, 42, 43, 44, 45 },
    { 51, 52, 53, 54, 55 }, { 61, 62, 63, 64, 65 },
    { 71, 72, 73, 74, 75 }, { 81, 82, 83, 84, 85 },
};

Or:

int array[5][8] =
{
    { 11, 12, 13, 14, 15, 21, 22, 23, },
    { 24, 25, 31, 32, 33, 34, 35, 41, },
    { 42, 43, 44, 45, 51, 52, 53, 54, },
    { 55, 61, 62, 63, 64, 65, 71, 72, },
    { 73, 74, 75, 81, 82, 83, 84, 85, },
};

I want 8 rows and 5 columns. Every set of 5 elements should be printed in 8 separate rows.

So you need int array[8][5] — 8 rows with 5 elements in each row. In a 2D array in C, the first index is the row, the second is the column. That means the outer loop runs over rows, the inner loop runs over columns.

#include <stdio.h>

int main(void)
{
    int array[8][5] =
    {
        { 11, 12, 13, 14, 15 }, { 21, 22, 23, 24, 25 },
        { 31, 32, 33, 34, 35 }, { 41, 42, 43, 44, 45 },
        { 51, 52, 53, 54, 55 }, { 61, 62, 63, 64, 65 },
        { 71, 72, 73, 74, 75 }, { 81, 82, 83, 84, 85 },
    };

    for (int row = 0; row < 8; row++)
    {
        for (int col = 0; col < 5; col++)
            printf(" %d", array[row][col]);
        putchar('\n');
    }
    return 0;
}

Output:

 11 12 13 14 15
 21 22 23 24 25
 31 32 33 34 35
 41 42 43 44 45
 51 52 53 54 55
 61 62 63 64 65
 71 72 73 74 75
 81 82 83 84 85