I'm writing a simple test program to pass multidimensional arrays. I've been struggling to get the signature of the callee function.
我正在编写一个简单的测试程序来通过多维数组。我一直在努力得到callee函数的签名。
The code I have:
我的代码:
void p(int (*s)[100], int n) { ... }
...
{
int s1[10][100], s2[10][1000];
p(s1, 100);
}
This code appears to work, but is not what I intended. I want the function p to be oblivious whether the range of values is either 100 or 1000, but should know there are 10 pointers (by use of function signature).
这段代码似乎可以工作,但不是我想要的。我希望函数p能够忽略值的范围是100还是1000,但是应该知道有10个指针(通过函数签名)。
As a first attempt:
第一次尝试:
void p(int (*s)[10], int n) // n = # elements in the range of the array
and as a second:
作为第二:
void p(int **s, int n) // n = # of elements in the range of the array
But to no avail can I seem to get these to work correctly. I don't want to hardcode the 100 or 1000 in the signature, but instead pass it in, keeping in mind there will always be 10 arrays.
但是,我似乎无法使它们正常工作。我不想在签名中硬编码100或1000,而是把它传递进来,记住总是会有10个数组。
Obviously, I want to avoid having to declare the function:
显然,我想避免必须声明函数:
void p(int *s1, int *s2, int *s3, ..., int *s10, int n)
FYI, I'm looking at the answers to a similar question but still confused.
顺便说一下,我正在看一个类似问题的答案,但还是很困惑。
2 个解决方案
#1
4
You need to transpose your arrays for this to work. Declare
你需要对数组进行变换才能让它工作。声明
int s1[100][10];
int s2[1000][10];
Now, you can pass these to a function like this:
现在,你可以把这些传递给这样的函数:
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
}
Because of the way the C type system works, an array argument can only be "flexible" in the sense you want in its left-most index.
由于C类型系统的工作方式,数组参数只能在最左索引中“灵活”。
#2
2
You could also create a struct
for the matrix and pass it to the function p
你也可以为矩阵创建一个结构体并将它传递给函数p
struct Matrix{
int **array;
int n;
int m;
};
void p(Matrix *k){
length=k->m;
width=k->n;
firstElement=k->array[0][0];
}
#1
4
You need to transpose your arrays for this to work. Declare
你需要对数组进行变换才能让它工作。声明
int s1[100][10];
int s2[1000][10];
Now, you can pass these to a function like this:
现在,你可以把这些传递给这样的函数:
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
}
Because of the way the C type system works, an array argument can only be "flexible" in the sense you want in its left-most index.
由于C类型系统的工作方式,数组参数只能在最左索引中“灵活”。
#2
2
You could also create a struct
for the matrix and pass it to the function p
你也可以为矩阵创建一个结构体并将它传递给函数p
struct Matrix{
int **array;
int n;
int m;
};
void p(Matrix *k){
length=k->m;
width=k->n;
firstElement=k->array[0][0];
}