将多维数组传递给函数

dan*_*dan 4 c arrays multidimensional-array

在扫描数组的大小之后,我需要能够将2D数组传递到扫描函数中。我到过的所有地方都告诉我,如果没有维,就无法将2D数组传递给函数,但是我不知道有其他方法可以做到。


void scan_arrays (int *array, int row, int column);

int main (void){

  int row;
  int column;

  printf("Enter sizes: ");
  scanf("%d %d",&row,&column);


  int firstarray[row][column];
  int secondarray[row][column];

  printf("Enter array 1 elements:\n");
  scan_arrays(&firstarray,row,column);

  printf("Enter array 2 elements:\n");
  scan_arrays(&secondarray,row,column);

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      printf("%d ",firstarray[i][j]);
    }
    printf("\n");
  }

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      printf("%d ",secondarray[i][j]);
    }
    printf("\n");
  }

  return 0;
}

void scan_arrays (int *array, int row, int column){

  for(int i = 0; i < row; i++){
    for(int j = 0; j < column; j++){
      scanf("%d",&array[i][j]);
    }
    printf("\n");
  }

}```
I've only been coding for a couple of months.
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 5

该函数应通过以下方式声明:

void scan_arrays (int row, int column, int array[row][column]);
Run Code Online (Sandbox Code Playgroud)

同样,对于函数定义的第一行。该rowcolumn参数必须是第一位的,让他们在范围上为自己在使用array参数。的row在阵列方向在技术上是多余的,但对于码自文档的简单方法。

该函数将被这样调用:

scan_arrays(row, column, firstarray)
Run Code Online (Sandbox Code Playgroud)

您的其余代码可以保持不变。


在定义数组之前对用户输入进行一些验证是一个好主意:如果它们输入垃圾0,,负数或大数导致堆栈溢出,则会引起麻烦。通过动态分配可以避免后面的问题:

int (*firstarray)[column] = malloc( sizeof(int[row][column]) );
if ( firstarray == NULL )
    // ...error handling
Run Code Online (Sandbox Code Playgroud)

并且使用的代码firstarray可以保持不变。