C:交换二维数组中值的函数

标签 c arrays function-parameter

我正在尝试编写一个函数来交换二维数组中的 2 个元素:

void swap(int surface[][], int x1, int y1, int x2, int y2) {
    int temp = surface[x1][y1];
    surface[x1][y1] = surface[x2][y2];
    surface[x2][y2] = temp;
}

然而,当我尝试编译它 (gcc) 时,我收到此错误消息:

Sim_Annealing.c: In function `swap': 
Sim_Annealing.c:7: error: invalid use of array with unspecified bounds
Sim_Annealing.c:8: error: invalid use of array with unspecified bounds
Sim_Annealing.c:8: error: invalid use of array with unspecified bounds
Sim_Annealing.c:9: error: invalid use of array with unspecified bounds

为了将二维数组作为函数参数,我必须做一些特殊的魔法吗?

感谢您的帮助。如果您知道数组作为函数参数的任何好的引用,请按照我的方式发送它们:)

最佳答案

只需声明数组参数即可。更好的是,对初始声明和函数的形式参数都使用 typedef。

问题是,如果不知道行大小,即列数,就无法计算指针调整以获得后续行。有趣的是,它不需要知道您有多少行。

例如,这个有效:

void swap(int surface[][20], int x1, int y1, int x2, int y2) {
  int temp = surface[x1][y1];
    surface[x1][y1] = surface[x2][y2];
    surface[x2][y2] = temp;
}

但最好将调用者的类型和函数的类型联系在一起。


每个下标访问都需要乘法,但这有效(仅符合 C99 的编译器)...

int f(int, int, int a[*][*]);

int f(int r, int c, int a[r][c])
{
  return a[99][100];
}

另一个例子,它甚至可以在 C89 之前的环境中工作:

typedef int surface_t[][20];

surface_t therealthing = {
  { 1, 2, 3},
  { 4, 5, 6}
};

void swap(surface_t x) {
  x[0][2] = 'q';
}

void f1(void) {
  swap(therealthing);
}

最后,由于可变长度数组是最近才出现的东西,所以传统且仍然是最快的技术是传递 int *a[]。这不需要任何行或列长度的知识,但您需要构造指针 vector 。

关于C:交换二维数组中值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1501217/

相关文章:

arrays - C 将大文本文件加载到数组中

c++ - 'std::string {aka std::basic_string<char>}' 分配中的类型不兼容

swift - 将类作为参数传递给快速返回此类对象的函数?

c - Go中有mmseg还是我可以从Go中调用自定义的C函数?

java - 字符串数组初始化作为构造函数参数

c - 保存一个程序的输入

sql - 具有重复参数的 PostgreSQL 函数

r- 使用 purrr::map 时存储警告消息而不丢弃结果

c - 结构数组 - C 中的内存释放

mysql - 将 sprintf 与 mysql_query 结合使用