请帮助传递多维数组

时间:2010-04-05 06:03:03

标签: c arrays types multidimensional-array arguments

我正在编写一个简单的测试程序来传递多维数组。我一直在努力获得被调用函数的签名。

我的代码:

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的答案,但仍然感到困惑。

2 个答案:

答案 0 :(得分:4)

您需要转置数组才能使其正常工作。声明

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类型系统的工作方式,数组参数在你最左边的索引中只能是“灵活的”。

答案 1 :(得分:2)

您还可以为矩阵创建struct并将其传递给函数p

struct Matrix{
     int **array;
     int n;
     int m;
};


void p(Matrix *k){
     length=k->m;
     width=k->n;
     firstElement=k->array[0][0];
}
相关问题