C:用于交换2D数组中的值的函数

Nop*_*ope 0 c arrays function-parameter

我正在尝试编写一个函数来交换2D数组中的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;
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译它(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
Run Code Online (Sandbox Code Playgroud)

为了将2D数组作为函数参数,我是否需要做一些特殊的魔术?

谢谢你的帮助.如果你知道有关数组的任何好的引用作为函数参数发送我的方式:)

Dig*_*oss 6

只需声明数组参数.更好的是,对初始声明和函数的形式参数使用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;
}
Run Code Online (Sandbox Code Playgroud)

但最好将调用者的类型和函数的类型绑定在一起.


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

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

int f(int r, int c, int a[r][c])
{
  return a[99][100];
}
Run Code Online (Sandbox Code Playgroud)

另一个例子,即使在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);
}
Run Code Online (Sandbox Code Playgroud)

最后,因为可变长度数组是最新的,传统的,仍然是最快的技术是通过int *a[].这不需要任何行或列长度的知识,但您需要构造指针向量.