如何在C中的函数中传递2D数组(矩阵)?

时间:2021-04-04 10:08:03

I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference?

我需要这样做才能在矩阵上持续操作。这是否意味着它需要通过引用传递?

Will this suffice?

这还够吗?

void operate_on_matrix(char matrix[][20]);

void operate_on_matrix(char matrix [] [20]);

4 个解决方案

#1


65  

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

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

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

1)使用数组数组。只有在编译时完全确定数组边界,或者编译器支持VLA时,才能使用此方法:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS])
{
  int i, j;

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

void func_vla(int rows, int cols, int array[rows][cols])
{
  int i, j;

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

int main()
{
  int x[ROWS][COLS];

  func(x);
  func_vla(x, rows, cols);
}

2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

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

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);
}

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

3)使用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*cols+j]=i*j;
    }
  }
}

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

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * cols * sizeof *x);

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

  /* deallocate the array */
  free(x);
}

#2


6  

I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:

我不知道你的意思是“数据不要丢失”。以下是将普通2D数组传递给函数的方法:

void myfunc(int arr[M][N]) { // M is optional, but N is required
  ..
}

int main() {
  int somearr[M][N];
  ...
  myfunc(somearr);
  ...
}

#3


-2  

If your compiler does not support VLAs, you can do it in simple way by passing the 2d array as int* with row and col. In the receiving function regenerate the 1d array index from 2d array indexes.

如果您的编译器不支持VLA,您可以通过将2d数组作为int * with row和col传递,以简单的方式完成。在接收函数中,从2d数组索引重新生成1d数组索引。

int 
getid(int row, int x, int y) {
          return (row*x+y);
}
void 
printMatrix(int*arr, int row, int col) {
     for(int x = 0; x < row ; x++) {
             printf("\n");
             for (int y = 0; y <col ; y++) {
                 printf("%d  ",arr[getid(row, x,y)]);
             } 
     }                     
}

main()
{

   int arr[2][2] = {11,12,21,22};
   int row = 2, col = 2;

   printMatrix((int*)arr, row, col);

 }

#4


-3  

     #include <iostream>
     using namespace std;

     void printarray(int *a, int c,int r)
     {
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < c; j++)
            {
                cout << "\t" << *(a + i*c + j) << "\t";  // a is a pointer refer to a 2D array
            }
        cout << endl << "\n\n";
        }
     }

     int main()
     {
         int array[4][4] = 
         {{1 ,2 ,3 ,4 },
          {12,13,14,5 },
          {11,16,15,6 },
          {10,9 ,8 ,7 }};

          printarray((int*)array,4,4);
          // here I use print function but u can use any other useful function like 
          //setArray((int *) array,4,4);

        return 0;
    }

#1


65  

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

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

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

1)使用数组数组。只有在编译时完全确定数组边界,或者编译器支持VLA时,才能使用此方法:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS])
{
  int i, j;

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

void func_vla(int rows, int cols, int array[rows][cols])
{
  int i, j;

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

int main()
{
  int x[ROWS][COLS];

  func(x);
  func_vla(x, rows, cols);
}

2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

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

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);
}

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

3)使用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*cols+j]=i*j;
    }
  }
}

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

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * cols * sizeof *x);

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

  /* deallocate the array */
  free(x);
}

#2


6  

I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:

我不知道你的意思是“数据不要丢失”。以下是将普通2D数组传递给函数的方法:

void myfunc(int arr[M][N]) { // M is optional, but N is required
  ..
}

int main() {
  int somearr[M][N];
  ...
  myfunc(somearr);
  ...
}

#3


-2  

If your compiler does not support VLAs, you can do it in simple way by passing the 2d array as int* with row and col. In the receiving function regenerate the 1d array index from 2d array indexes.

如果您的编译器不支持VLA,您可以通过将2d数组作为int * with row和col传递,以简单的方式完成。在接收函数中,从2d数组索引重新生成1d数组索引。

int 
getid(int row, int x, int y) {
          return (row*x+y);
}
void 
printMatrix(int*arr, int row, int col) {
     for(int x = 0; x < row ; x++) {
             printf("\n");
             for (int y = 0; y <col ; y++) {
                 printf("%d  ",arr[getid(row, x,y)]);
             } 
     }                     
}

main()
{

   int arr[2][2] = {11,12,21,22};
   int row = 2, col = 2;

   printMatrix((int*)arr, row, col);

 }

#4


-3  

     #include <iostream>
     using namespace std;

     void printarray(int *a, int c,int r)
     {
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < c; j++)
            {
                cout << "\t" << *(a + i*c + j) << "\t";  // a is a pointer refer to a 2D array
            }
        cout << endl << "\n\n";
        }
     }

     int main()
     {
         int array[4][4] = 
         {{1 ,2 ,3 ,4 },
          {12,13,14,5 },
          {11,16,15,6 },
          {10,9 ,8 ,7 }};

          printarray((int*)array,4,4);
          // here I use print function but u can use any other useful function like 
          //setArray((int *) array,4,4);

        return 0;
    }