Real noob question no doubt, but I can’t get my head around this behaviour. I initialise a 2-d array, then call a function to print out certain values from it. The program and result are shown below:
int
main(void)
{
int matrix[3][5] =
{
{14,7,6,55,2},
{8,33,12,88,24},
{19,20,21,90,7}
};
printArray(3, 5, matrix);
printArray(2, 3, matrix);
return 0;
}
void
printArray(int rows, int columns, int matrix[rows][columns])
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
printf("%3i ", matrix[i][j]);
printf("\n");
}
printf("\n");
}
14 7 6 55 2
8 33 12 88 24
19 20 21 90 7
14 7 6
55 2 8
It seems that the second time printArray() is called it continues printing values from the first row on a new line rather than actually accessing the next row. I don’t understand this as surely the index values are constant aren’t they? (ie matrix[1][2] should be (in this case) 12, not 8.
Thanks in advance.
The following:
promises the compiler that the third argument has the dimensions
rowsxcolumns.At the same time, the following line breaks this promise:
since
matrixis3x5and not2x3.If you only wish to print a subset of rows and columns, you could do something like: