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?
You have:
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.Or:
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.Output: