2009-04-28 111 views
4

我有一些二维阵列,如:阵列指针到多维数组

int shape1[3][5] = {1,0,0, 
      1,0,0, 
      1,0,0, 
      1,0,0, 
      1,0,0}; 
int shape2[3][5] = {0,0,0, 
      0,0,0, 
      0,1,1, 
      1,1,0, 
      0,1,0}; 

等。

我该如何制作指向这些指针的数组?

我尝试以下,但他们没有工作

int *shapes[]= {&shape1,&shape2}; 

int *shapes[]= {shape1,shape2}; 

int **shapes[]= {&shape1,shape2}; 

任何帮助:(警告:从兼容的指针类型初始化)?

回答

3

更新固定式。感谢j_radom_hacker将此引起我的注意!

[编辑:其实这里的类型是不正确的 - 看到Robert S. Barnes' answer正确类型使用。]

搞清楚shape1第一类型和shape2

typedef int (*shape_array_t)[5]; 

现在使用这个:

shape_array_t sat[] = { shape1, shape2 }; 
+0

谢谢,但它仍然yelds相同错误! – pistacchio 2009-04-28 19:16:48

+0

嘿,我犯了一个错字 - 对不起,有关:P – dirkgently 2009-04-28 19:17:31

3

首先,第一个数组绑定指向s到最外面的阵列尺寸,所以你应该声明shape1为:

int shape1[5][3] = {1,0,0, 
        1,0,0, 
        1,0,0, 
        1,0,0, 
        1,0,0}; 

,类似的还有shape2

[编辑:我已经改变了下面shapes类型对应Robert Barnes' answer - 我们不希望被包含在这种类型的最外面的下标!]

略带奇怪的类型名称你需要的是:

int (*shapes[])[3] = { shape1, shape2 }; 

这使得元件的4排,使用加以解决shape2 1列

shapes[1][3][0] 

击穿子表达式和它们的C类型:

shapes   // has type "int (*x[2])[3]" (decays to "(**x)[3]") 
shapes[1]   // has type "int (*x)[3]" 
shapes[1][3]  // has type "int x[3]" (decays to "int *x") 
shapes[1][3][0] // has type "int x" 

(请注意,伪x已包括在上述的类型,以使它们更清晰 - 事实上这个标识符不是所述类型的一部分。)

解码C/C++类型的经验法则是“从变量名开始,在可以时读取正确的值,当您敲下右括号时离开。因此,shapes的解码类型名是:

指向3个整数数组的指针数组。

一般来说,使用typedef s作为dirkgently suggests这些复杂类型会更好。

5

我相信我刚刚证实我写的是正确的。如预期了以下工作:

#include <stdio.h> 

int main(int argc, char **argv) { 

int shape1[5][3] = {1,0,0, 
       1,0,0, 
       1,0,0, 
       1,0,0, 
       1,0,0}; 

int shape2[5][3] = {0,0,0, 
       0,0,0, 
       0,1,1, 
       1,1,0, 
       0,1,0}; 

typedef int (*shapes_p)[3]; 
shapes_p shapes[2] = { shape1, shape2 }; 

shapes[0][1][0] = 5; 
shapes[1][1][0] = 5; 

printf("shape1[1][0] == %d\n", shape1[1][0]); 
printf("shape2[1][0] == %d\n", shape2[1][0]); 

} 

需要记住的是,shape1shape2类型居然是:

int *shape1[5];

你在内存中有什么是每5个整数的3个相邻阵列。但是实际的类型是指向5个整数的指针。当你写:

shape1[1][2] = 1;

你告诉编译器索引到INT [5]的第二阵列然后访问该阵列的第三元件。编译器实际上做的是指向底层类型的指针运算,在这种情况下是int [5]。你可以做同样的用下面的代码:

int *p = shapes1[0]; 
p+7 = 1; // same as shape1[1][2] = 1; 

所以,如果你想指针数组为int * [5],那么你会怎么做:

typedef int (*shapes_p)[5]; 
shapes_p shapes[2];