C语言将2D数组作为参数传递

时间:2017-07-30 17:48:09

标签: c

给出以下代码:

void myfunc(int** a){
   int temp=a[0][0];

}

int test[3][3] = {{1, 2, 3},
                   {4, 5, 6},
                   {7, 8, 9}};
myfunc(test);

我正在尝试将二维数组测试作为int**传递给myfunc,但我的程序崩溃了。 (我已经阅读了一些代码示例,使用像a[][]这样的参数作为参数,但是如果我想使用int**,那么如何在我的函数中访问2D数组呢?

1 个答案:

答案 0 :(得分:1)

C实际上没有多维数组,但有几种方法可以模拟它们。将这些数组传递给函数的方法取决于模拟多维的方式:

1.使用(动态分配的)指针数组(动态分配)数组。这主要用于直到运行时才知道数组边界。

void func(int** array, int rows, int cols)
    {
      int i, j;

      for (i=0; i<rows; i++)
      {
        for (j=0; j<cols; j++)
        {
          array[i][j] = i*j;
        }
      }
    }

    int main()
    {
      int rows, cols, i;
      int **x;

      /* obtain values for rows & cols */

      /* allocate the array */
      x = malloc(rows * sizeof *x);
      for (i=0; i<rows; i++)
      {
        x[i] = malloc(cols * sizeof *x[i]);
      }

      /* use the array */
      func(x, rows, cols);

      /* deallocate the array */
      for (i=0; i<rows; i++)
      {
        free(x[i]);
      }
      free(x);
    }


2.当两个维度全局可用时(作为宏或作为全局常量)。

#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    print(arr);
    return 0;
}
相关问题