C语言 如何在C中的函数中传递二维数组(矩阵)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3911400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:40:09  来源:igfitidea点击:

How to pass 2D array (matrix) in a function in C?

cmultidimensional-arrayparameter-passing

提问by Shweta

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

回答by Bart van Ingen Schenau

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(ROWS, COLS, x);
}

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) 使用一维数组并修正索引。这可以用于静态分配(固定大小)和动态分配的数组:

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

4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.

4) 使用动态分配的 VLA。与选项 2 相比,它的一个优点是只有一个内存分配;另一个是需要更少的内存,因为不需要指针数组。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);

void func_vla(int rows, int cols, int array[rows][cols])
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            array[i][j] = (i + 1) * (j + 1);
        }
    }
}

int main(void)
{
    int rows, cols;

    get_rows_cols(&rows, &cols);

    int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
    /* error check omitted */

    func_vla(rows, cols, array);
    dump_array("After initialization", rows, cols, array);

    free(array);
    return 0;
}

void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
    printf("%s (%dx%d):\n", tag, rows, cols);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
            printf("%4d", array[i][j]);
        putchar('\n');
    }
}

void get_rows_cols(int *rows, int *cols)
{
    srand(time(0));           // Only acceptable because it is called once
    *rows = 5 + rand() % 10;
    *cols = 3 + rand() % 12;
}

(See srand()— why call it only once?.)

(看srand()——为什么只调用一次?。)

回答by casablanca

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

我不知道您所说的“数据不会丢失”是什么意思。以下是将普通二维数组传递给函数的方法:

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

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

回答by Minhas Kamal

Easiest Way: Passing A Variable-Length 2D Array

最简单的方法:传递可变长度的二维数组

Most clean technique for both C & C++ is: to pass 2D array like a 1D array, then use as 2D inside the function.

C 和 C++ 最干净的技术是:像一维数组一样传递二维数组,然后在函数内部用作二维数组。

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {1, 2, 3}, {7, 8, 9} };
    func(2, 3, matrix[0]);

    return 0;
}

回答by shinxg

2D array:

二维数组:

int sum(int array[][COLS], int rows)
{

}

3D array:

3D阵列:

int sum(int array[][B][C], int A)
{

}

4D array:

4D阵列:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

和 nD 数组:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

回答by Casper Ghost

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