该程序的目标是操作二维数组内的数据。
int main(void)
{
int array[500][500];
int x0, y0;
if ( input(array, &x0, &y0)==0 )
return 1;
return 0;
}
int input( int array, int *x0, int *y0 ) {
int x = 0;
int y = 0;
int err = 0;
char c;
printf("Enter sizes:\n");
if ( scanf("%d %d", x0, y0)!=2 || *x0<=0 || *y0<=0 || *x0>500 || *y0>500 ) {
printf("Invalid input.\n");
return 0;
}
while ( y < *y0 ) {
x = 0;
while ( x < *x0 ) { //reading entries in x coordinate
c = getchar();
switch(c) {
case 'o' : array[y][x] = 1; break;
case '.' : array[y][x] = 0; break;
case '!' : array[y][x] = 2; break;
default : err = 1; break;
}
x++;
}
if( x!=*x0 )
err=1;
y++; //move to another "line"
}
if (y!=*y0)
err=1;
if (err==1) {
printf("Invalid input.\n");
return 0;
}
return 1;
}
程序首先获取数组的维度,然后获取三个字母之一:o
, !
或.
例如:
3 3
ooo
.!o
...
问题是我的函数不接受它的参数: input(array, &x0, &y0)
这导致我无法写入 switch
中的该数组。在前一种情况下passing argument 1 of 'input' makes integer from pointer without a cast
而后者subscripted value is neither array nor pointer nor vector.
我之前的程序使用了一维数组,这种将数组传递给函数的方法是有效的。
那么我应该如何将数组作为参数传递给函数呢?提前致谢。
最佳答案
将 main
函数的代码移到 input
函数之后,以便在编译 main 时知道
.input
的原型(prototype)
将输入
的原型(prototype)更改为:
int input(int array[500][500], int *x0, int *y0) {
您的代码还存在其他问题。例如,您没有正确处理每个矩阵行后输入的换行符。
关于c - 将二维数组作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34111984/