How to pass a two-dimensional array as a parameter in C language?
In C language, two methods can be used to pass a two-dimensional array as a parameter to a function:
- Passing arrays using pointers.
- Pass the address of the first element of the 2D array as a parameter to the function.
- Access array elements through pointer operations in the function.
- The sample code is as follows:
- void func(int (*arr)[M], int row, int col) {
// Access array elements using pointers
for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%d ", arr[i][j]); } printf("\n"); } } int main() { int arr[N][M] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int row = N; int col = M; // Pass the array's base address as a parameter to the function func(arr, row, col); return 0; } - Passing an array using a one-dimensional array:
- Convert a two-dimensional array into a one-dimensional array.
- Pass the address of the first element of a one-dimensional array as a parameter to the function.
- In a function, accessing array elements is done by computing the index.
- Here is the example code:
- void func(int *arr, int row, int col) {
// Access array elements using index calculation
for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%d ", arr[i * col + j]); } printf("\n"); } } int main() { int arr[N][M] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int row = N; int col = M; // Convert the 2D array to a 1D array and pass the array's address as a parameter to the function func((int *)arr, row, col); return 0; }
Both methods can be used to pass a two-dimensional array as a parameter to a function, the choice depends on the specific needs and programming habits.