简体   繁体   中英

Passing multidimensional arrays to functions?

I have a function setPosition declared like:

void setPosition(char ***grid, int a, int b) {
    int x = a / 8;
    int xbit = a % 8;
    int y = b;
    (*grid)[x][y] |= 1 << xbit;
}

and in my main, I have:

char grid[1000][1000];
setPosition(&grid, 10, 5);

But I get "warning: passing argument 1 of 'setPosition' from incompatible pointer type". why?

Arrays and pointers are not the same type, even though arrays do decay to pointers when passed to functions. You can change the method signature to take an array

void setPosition(char grid[][1000], Pos *p)

but if you are doing C++, vector<vector<char> > would provide a much better and more flexible option.

Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T " will be converted to / replaced with / "decay" to an expression of type "pointer to T " whose value is the address of the first element in the array.

If you call your function as

setPosition(grid, 10, 5);

the expression grid will have type char [1000][1000] , which by the rule above will be replaced with an expression of type char (*)[1000] , so your function prototype would need to be

void setPosition(char (*grid)[1000], int a, int b) { ... }

or

void setPosition(char grid[][1000], int a, int b) { ... }

which in this context is the same thing.

If you call your function as

setPosition(&grid, 10, 5);

then the expression &grid has type char (*)[1000][1000] , so your function prototype would need to be

void setPosition(char (*grid)[1000][1000], int a, int b) { ... }

and you would need to explicitly dereference grid before applying any subscript, as in

(*grid)[a][b] = ...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM