2

This is my code and it is not working. It generate these errors when I pass char array like this grid[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]

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

It generate these errors when I pass char array like this 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

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;
}
14
  • 1
    It's important to realize that you cannot actually pass an array to a function, regardless of what your function signature looks like. Arrays will decay to pointers to their first element in this situation. Commented Oct 21, 2014 at 21:04
  • Also, what compiler are you using? Commented Oct 21, 2014 at 21:06
  • 1
    Is there any solution other than pointers?? Commented Oct 21, 2014 at 21:06
  • 1
    @IskarJarak I am using Dev C++ 5.4 Commented Oct 21, 2014 at 21:07
  • 1
    it will work.(Should be treated as a char * instead of a 2D array.) also scanf("%s[^\\n]%*c", grid[i]); wrong. Commented Oct 21, 2014 at 21:30

1 Answer 1

4

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

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

this will print `grid[n][m]

Sign up to request clarification or add additional context in comments.

9 Comments

sorry, forgot to pass it in, c is just the variable you're passing into your own function that corresponds to columns
But it is still not working. It didn't print anything. My dimensions of char array are r and c and I wrote it as (grid+r*c)[c]. Am I wrong or right??
So what should I do? Will you explain me??
I wrote it like this printf("%c", (grid+i*j)[c]). i = the no of row i want to access and j = the no of column i want to access and c = total no of columns. It still not working and print garbage.
Ok Thanks Finally Worked :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.