我正在编写一个简单的测试程序来传递多维数组。我一直在努力获取被调用函数的签名。
我的代码:
void p(int (*s)[100], int n) { ... }
...
{
int s1[10][100], s2[10][1000];
p(s1, 100);
}
这段代码似乎可以工作,但不是我想要的。我希望函数 p 不知道值的范围是 100 还是 1000,但应该知道有 10 个指针(通过使用函数签名)。
作为第一次尝试:
void p(int (*s)[10], int n) // n = # elements in the range of the array
第二个:
void p(int **s, int n) // n = # of elements in the range of the array
但我似乎无法让这些正常工作。我不想在签名中对 100 或 1000 进行硬编码,而是将其传递进去,请记住总会有 10 个数组。
显然,我想避免声明该函数:
void p(int *s1, int *s2, int *s3, ..., int *s10, int n)
仅供引用,我正在查看 a similar question 的答案但还是很困惑。
最佳答案
您需要转置数组才能使其工作。声明
int s1[100][10];
int s2[1000][10];
现在,您可以将它们传递给如下函数:
void foo(int (*s)[10], int n) {
/* various declarations */
for (i = 0; i < n; i++)
for (j = 0; j < 10; j++)
s[i][j] += 1
}
由于 C 类型系统的工作方式,数组参数只能在您希望在其最左侧索引中实现的意义上“灵活”。
关于c - 请帮忙传递多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2577127/