C:用于在2D数组中交换值的函数 [英] C: Function to swap values in 2D array

查看:114
本文介绍了C:用于在2D数组中交换值的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a function to swap 2 elements in a 2D array:

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)时,出现以下错误消息:

however when I try to compile it (gcc), I get this error message:

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

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

Is there some special magic I have to do in order to have a 2D array as a function parameter?

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

Thanks for your help. If you know of any good references for arrays as function parameters send them my way :)

推荐答案

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

Just declare the array parameters. Better yet, use a typedef for both the initial declaration and the function's formal parameter.

问题在于,在不知道行大小(即列数)的情况下,它无法计算指针调整以获取后续行.有趣的是,它不需要知道您有多少行.

The problem is that without knowing the row size, i.e., the number of columns, it has no way to compute the pointer adjustment to get subsequent rows. Interestingly, it does not need to know how many rows you have.

例如,这有效:

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;
}

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

But it would be better to tie the caller's types and the function's type together.

每个下标访问都将需要一个乘法,但这是可行的(仅符合C99的编译器)...

Every subscript access will require a multiply, but this works (only C99-conforming compilers) ...

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

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

另一个示例,即使在C89之前的环境中也可以使用:

Another example, which would work in even pre-C89 environments:

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[].不需要任何关于行或列长度的知识,但是您确实需要构造指针向量.

And finally, because variable length arrays are something quite recent, the traditional and still the fastest technique is to pass int *a[]. This doesn't require any knowledge of either row or column lengths, but you do need to construct the pointer vector.

这篇关于C:用于在2D数组中交换值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆