代码之家  ›  专栏  ›  技术社区  ›  pistacchio

指向多维数组的指针数组

  •  4
  • pistacchio  · 技术社区  · 16 年前

    我有一些二维数组,如:

    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 回复  |  直到 16 年前
        1
  •  5
  •   Robert S. Barnes Antoni    16 年前

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

    #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]);
    
    }
    

    要记住的是 shape1 shape2 实际上是:

    int *shape1[5];

    内存中有3个相邻的数组,每个数组有5个整数。但实际类型是指向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];
    
        2
  •  3
  •   Community CDub    8 年前

    首先,第一个数组绑定引用最外层的数组维度,因此您可能应该声明 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 };
    

    形状2 使用

    shapes[1][3][0]
    

    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++类型的一条经验法则是“从变量名开始,可以的时候向右读,碰到右括号的时候向左读” 是:

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

    一般来说,使用它会更好 typedef dirkgently suggests

        3
  •  3
  •   Community CDub    8 年前

    更新 固定类型。谢谢 j_radom_hacker 谢谢你让我注意到这一点!

    Robert S. Barnes' answer 以获取要使用的正确类型。]

    shape1 shape2 第一:

    typedef int (*shape_array_t)[5];
    

    现在用这个:

    shape_array_t sat[] = { shape1, shape2 };