如何在C中传入一个多维char数组?

时间:2022-05-07 22:55:42

This is my code and it is not working. It generate these errors when I pass char array like this grid[r][c]

这是我的代码,它不起作用。当我像这个网格传递char数组时,它会产生这些错误[r] [c]

[Error] use of parameter 'r' outside function body

[Error] use of parameter 'c' outside function body

It generate these errors when I pass char array like this grid[][c]

当我传递char数组时会产生这些错误,就像这个grid [] [c]

[Error] use of parameter 'c' outside function body

It generate these errors when I pass char array like this grid[][]

当我传递char数组时会产生这些错误,就像这个grid [] []

[Error] declaration of 'grid' as multidimensional array must have bounds for all dimensions except the first 

And it runs perfectly fine when I pass this like this grid[1][2] i.e. just passing with an integer.0

当我像这个网格[1] [2]那样传递它时,它运行完全正常,即只传递一个整数0

I am stuck here and I don't know what to do or what not??

我被困在这里,我不知道该做什么或不做什么?

How to get rid of this problem?? Help Me !!!

如何摆脱这个问题?帮我 !!!

Thanks in Advance!

提前致谢!

void dfs(int r, int c, int pacman_r, int pacman_c, int food_r, int food_c, char grid[r][c]) {
    //logic here
}
int main(void) {
    int r, c;
    int pacman_r, pacman_c;
    int food_r, food_c;
    scanf( "%d %d", &pacman_r, &pacman_c);
    scanf( "%d %d", &food_r, &food_c);
    scanf( "%d %d", &r, &c);
    char grid[r][c];
    for( int i=0; i<r; i++) {
        scanf("%s[^\\n]%*c", grid[i]);
    }
    dfs( r, c, pacman_r, pacman_c, food_r, food_c, grid);
    return 0;
}

1 个解决方案

#1


3  

you should pass the argument as a char* then work with it as a pointer to a flattened instance of your array

你应该将参数作为char *传递,然后使用它作为指向数组的展平实例的指针

void fn(char* grid, int c){
    printf("%c", (grid+n*c)[m]);
}

this will print `grid[n][m]

这将打印`grid [n] [m]

#1


3  

you should pass the argument as a char* then work with it as a pointer to a flattened instance of your array

你应该将参数作为char *传递,然后使用它作为指向数组的展平实例的指针

void fn(char* grid, int c){
    printf("%c", (grid+n*c)[m]);
}

this will print `grid[n][m]

这将打印`grid [n] [m]