[英]Passing Multidimensional Arrays into a Function
在扫描数组的大小后,我需要能够将二维数组传递给扫描 function。 我看过的所有地方都告诉我,您不能将没有尺寸的 2D arrays 传递到 function 中,但我不知道有任何其他方法可以做到这一点。
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.
function 应该这样声明:
void scan_arrays (int row, int column, int array[row][column]);
同样对于 function 定义的第一行。 row
和column
参数必须先出现,以便它们在 scope 中用于array
参数。 数组维度中的row
技术上是多余的,但代码自我记录是一种简单的方法。
function 会这样调用:
scan_arrays(row, column, firstarray)
并且您的代码的 rest 可以保持不变。
在定义 arrays 之前对用户输入进行一些验证是个好主意:如果他们输入垃圾、 0
、负数或导致堆栈溢出的大数,则会导致麻烦。 后一个问题可以通过动态分配来避免:
int (*firstarray)[column] = malloc( sizeof(int[row][column]) );
if ( firstarray == NULL )
// ...error handling
并且使用firstarray
的代码可以保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.