I was trying to pass array of arrays to a function, but I am not getting correct results. I looked at [this SO post][1] for this purpose. I am not getting any warnings and I am using TDM GCC 64 compiler. What could be wrong with this code?
#include <stdio.h>
#include<inttypes.h>
void printArrayOfArrays(uint8_t numRows,uint8_t numColumns,int arraOfArray[][numColumns]);
int main(void)
{
int numRows, numColumns, rowCount, colCount, first[5][5];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &numRows, &numColumns);
printf("Enter the elements of first matrix\n");
for (rowCount = 0; rowCount < numRows; rowCount++)
{
for (colCount = 0; colCount < numColumns; colCount++)
{
scanf("%d", &first[rowCount][colCount]);
}
}
for (rowCount = 0; rowCount < numRows; rowCount++)
{
for (colCount = 0 ; colCount < numColumns; colCount++)
{
printf("%d\t",first[rowCount][colCount]);
}
printf("\n\n");
}
printf("\n");
printArrayOfArrays(numRows,numColumns,first);
return(0);
}
void printArrayOfArrays(uint8_t numRows,uint8_t numColumns,int arrayOfArray[numRows][numColumns])
{
for (uint8_t rowCount = 0; rowCount < numRows; rowCount++)
{
for (uint8_t colCount = 0 ; colCount < numColumns; colCount++)
{
printf("%d\t", *(*(arrayOfArray+rowCount)+colCount));
}
printf("\n");
}
}
The result I am getting for this is
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
4
3
1
6
4 3
1 6
4 3
0 0
Your array definitions of first
in main
and of arrayOfArrays
in printArrayOfArrays
are not consistent: first
is a 5×5 array, even if you don't use or initialise all elements; arrayOfArrays
is a variable length array, in your example 2×2.
So you should either make first
a variable length array, too:
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &numRows, &numColumns);
int first[numRows][numColumns];
(Make sure that you define it only after numRows
and numColumns
have meaningful values.)
Or you could make the parameter to the function a fixed size array of 5×5:
void printArrayOfArrays(uint8_t numRows, uint8_t numColumns,
int arrayOfArray[5][5]);
(In this case, you must ensure that numRows
and numColumns
don't exceed 5.)