To pass multidimensional arrays to a function, only the name of the array is passed to the function (similar to one-dimensional arrays).
Example 3: Pass two-dimensional arrays
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
// pass multi-dimensional array to a function
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers: 2 3 4 5 Displaying: 2 3 4 5
Notice the parameter int num[2][2]
in the function prototype and function definition:
// function prototype
void displayNumbers(int num[2][2]);
This signifies that the function takes a two-dimensional array as an argument. We can also pass arrays with more than 2 dimensions as a function argument.
When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified.
For example,
void displayNumbers(int num[][2]) {
// code
}