简体   繁体   English

将多维数组传递给函数?

[英]Passing multidimensional arrays to functions?

I have a function setPosition declared like: 我有一个函数setPosition声明为:

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". 但是我得到“警告:从不兼容的指针类型传递'setPosition'的参数1”。 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. 但是,如果您使用的是C ++, vector<vector<char> >将提供更好,更灵活的选择。

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. 除非它是sizeof或一元&运算符的操作数,或者是用于在声明中初始化另一个数组的字符串文字,否则类型为“ T N元素数组”的表达式将转换为/,并替换为/“ “衰减”到类型为“指向T指针”的表达式,其值是数组中第一个元素的地址。

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 表达式grid类型将为char [1000][1000] ,根据上述规则,该类型将替换为char (*)[1000]类型的表达式,因此您的函数原型必须为

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 那么表达式&grid类型为char (*)[1000][1000] ,因此您的函数原型需要为

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 ,如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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