Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of pointers to multidimensional arrays

Tags:

arrays

c

pointers

i have some bidimensional arrays like:

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};

and so on.

How can i make an array of pointers to those?

I tried the following, but they don't work (warning: initialization from incompatible pointer type):

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

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

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

Any help?

like image 244
pistacchio Avatar asked Dec 22 '22 11:12

pistacchio


1 Answers

I believe I just verified what I wrote was correct. The following works as expected:

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

}

The thing to remember is that the type of shape1 and shape2 is actually:

int *shape1[5];

What you have in memory is 3 adjacent arrays of 5 ints each. But the actual type is pointer to array of 5 ints. When you write:

shape1[1][2] = 1;

you're telling the compiler to index to the second array of int[5] and then access the 3rd element of that array. What the compiler actually does is pointer arithmetic on the underlying type pointed to, in this case int[5]. You could do the same with the following code:

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

So if you want an array of pointers to int *[5] then you would do:

typedef int (*shapes_p)[5];
shapes_p shapes[2];
like image 135
Robert S. Barnes Avatar answered Jan 09 '23 09:01

Robert S. Barnes