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:

  1. Passing arrays using pointers.
  2. Pass the address of the first element of the 2D array as a parameter to the function.
  3. Access array elements through pointer operations in the function.
  4. The sample code is as follows:
  5. 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; }
  6. Passing an array using a one-dimensional array:
  7. Convert a two-dimensional array into a one-dimensional array.
  8. Pass the address of the first element of a one-dimensional array as a parameter to the function.
  9. In a function, accessing array elements is done by computing the index.
  10. Here is the example code:
  11. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds