-
Filling 2D Array
Hello!
So here is the C code:
Code:
#include <stdio.h>
int main(void)
{
//2D Array
int array[2][2];
int number = 1;
//fill the array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
array[j][i]=number;
number+=1;
}
}
/* The Code Above Is To Print The Array */
//column number
int column=0;
for(int i=0;i<3;i++)
{
//column number
printf("%d %d %d\n",array[column][i],array[column+1][i],array[column+2][i]);
}
}
Can someone explain why the output is:
0 7 8
4 5 6
7 8 9
and not
1 2 3
4 5 6
7 8 9
The array is not filled incorrectly for some reason, more specifically the first row.
The first two cycles of the for loop seem to work correctly. One if the bugs seems to occur on the third. when array[0][2] is filled with number 7, for some reason array[1][0] changes it value to 7 as well.
Thanks in advance!
-
Because you have j and i swapped inside the inner for loop.
Code:
array[j][i]=number;
C is row major, and apparently you are trying to print it that way, but have column major code.
-
> for(int i=0;i<3;i++)
But your array is only 2x2, so this is a large buffer overrun.