c - 将多维数组传递给 C 中的函数

标签 c function multidimensional-array parameter-passing

根据我对数组是指针的理解,我编写了这个函数来交换多维数组中的值。

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/

相关文章:

iphone - C/Objective-c 中的二维数组

algorithm - 使用旋转和交换对二维环形阵列进行排序

c - 如何将 char 转换为 unsigned int?

Javascript回调函数问题

oracle - 从 PLSQL 中的表派生函数

c - C 中的一个程序,用于获取前两个小于给定数字的斐波那契数

php - 仅使用mysql查询从第二个表中获取第一个表作为数组的记录

c++ - 缓冲区溢出不影响 const 变量?

c - 如何获取输入的第二个字符串

c - C语言中如何读取一组字符?