根据我对数组是指针的理解,我编写了这个函数来交换多维数组中的值。
void
swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
但是当我尝试使用该功能时
swap(board[d-1][d-2]), board[d-1][d-33];
我从编译器中得到这些错误,我不知道为什么:
fifteen.c: in function 'init':
fifteen.c:166:9: error: passing argument 1 of 'swap' makes pointer from integer without a cast [-werror]
fifteen.c:45:6: note: expected 'int *' but argument is of type 'int'
fifteen.c:166:9: error: passing argument 2 of 'swap' makes pointer from integer without a cast [-werror]
fifteen.c:45:6: note: expected 'int *' but argument is of type 'int'
我该如何解决?
最佳答案
board[d-1][d-2]
和 board[d-1][d-33]
是 int
。要交换两者,您必须传递它们的地址:
swap (&board[d - 1][d - 2]), &board[d - 1][d - 33];
如果您正在使用 swap (board[d - 1][d - 2]), &board[d - 1][d - 33])
,指令 int tmp = *a;
将尝试访问地址 board[d - 1][d - 2]
上的值:这毫无意义!因为您使用的是指针,所以您必须传递变量的地址。
关于c - 将多维数组传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13102251/