c - 将二维数组作为参数传递给函数

标签 c arrays function pointers

该程序的目标是操作二维数组内的数据。

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/

相关文章:

c - 元组的写入约束

c - 基于斐波那契递归缓存

javascript hackerranks sherlock 和数组性能问题

c++ - 在 C++ 中声明返回字符串的函数

python - 一个函数中的一个函数是否会比单独定义这两个函数占用更多的 RAM 内存?

python - 从元组列表生成邻接矩阵的更优雅的方法

c - 如何使用 Windows API 创建文件?

c - Switch 语句未编译

c++ - 概念指针数组

c# - 统一3D : Load sprites from a folder