Can somebody please tell me what is wrong here?
int arr[15][1];
int main()
{
int x;
for(x=0; x<15; x++)
{
arr[x][0] = x;
arr[x][1] = x;
}
int y;
for(y=0; y<15; y++)
{
printf("[%d][0]=%u\t", y, arr[y][0]);
printf("[%d][1]=%u\n", y, arr[y][1]);
}
}
it gives me the below output, I can’t figure out what’s wrong, while the output for [0][0] and [0][1] should be 0, 0 and so on for the rest?
[0][0]=0 [0][1]=1
[1][0]=1 [1][1]=2
[2][0]=2 [2][1]=3
[3][0]=3 [3][1]=4
[4][0]=4 [4][1]=5
[5][0]=5 [5][1]=6
[6][0]=6 [6][1]=7
[7][0]=7 [7][1]=8
[8][0]=8 [8][1]=9
[9][0]=9 [9][1]=10
[10][0]=10 [10][1]=11
[11][0]=11 [11][1]=12
[12][0]=12 [12][1]=13
[13][0]=13 [13][1]=14
[14][0]=14 [14][1]=14
Here
you declare an array of 15×1 elements (so indices 0-14 for the first dimension and 0-0 for the second dimension), then you set the 0 and 1 elements of the second dimensions. As there is no element 1 of the second dimension,
arr[x][1] = x;is the same asarr[x+1][0] = x;Basically, an array is a contiguous memory to store elements. A multi-dimentional array can be though of as an array of arrays: the second dimension is repreated the size of the first dimention times. So when you overindex the second dimension, you are accessing the next element of the first dimension
This also means that
arr[x][1] = xaccesses memory that was not allocated for the array whenx==14You most likely meant to have two elements in the second dimension, so declare the array as: