A two-dimensional array can be passed to a function by specifying the number of columns in the parameter declaration. The function receives access to the array elements, while the row count can be supplied as a separate argument.
#include <stdio.h>
void displayMatrix(int rows, int matrix[][3])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
displayMatrix(2, matrix);
return 0;
}
Example Output #
10 20 30
40 50 60
Explanation #
The function parameter:
void displayMatrix(int rows, int matrix[][3])
specifies a two-dimensional array whose rows contain three integers. The first dimension is omitted because the function receives the row count separately.
The parameter matrix[][3] is adjusted to a pointer to an array of three integers. This preserves the row structure required for expressions such as matrix[i][j].
The nested loops access each element using its row and column indices:
printf("%d ", matrix[i][j]);
The rows argument determines how many rows are processed, while the column count is fixed at three.
Two-Dimensional Array Parameters #
| Parameter declaration | Meaning |
|---|---|
int matrix[][3] |
Pointer to rows containing three integers |
int matrix[2][3] |
Adjusted parameter type is still a pointer to rows of three integers |
int matrix[][columns] |
Can use a variable-length array parameter when supported and columns is available |
const int matrix[][3] |
Allows reading elements without modifying them through this parameter |
The column dimension must be known to calculate the correct address for each row. In C99 and later, variable-length array parameters can be used to accept runtime column counts, subject to implementation support.