Go through the layers of the array using the pointer to the array layer

|--------| // / |4 4 4 | // |--------| 4 | // / |3 3 3 | 4 | // |---------|3 | | // / | 2 2 2 |3 | / // |---------|2 |__| // | 1 1 1 |2 | / // | 1 1 1 |__| // | 1 1 1 | / // |_________| double arr[4][3][3] = {{1,1,1,1,1,1,1,1,1},{2,2,2,2,2,2,2,2,2},{3,3,3,3,3,3,3,3,3},{4,4,4,4,4,4,4,4,4}}; 

I believe that this array consists of 4 layers.

I want to create a pointer to an array layer and go through the layers of this array using a pointer.

I'm trying to:

 double (*pp1)[sizeof(arr[0]) / sizeof(ar[0][0][0])]; pp1 = arr[0]; 

and get an error from intelIsense: a value of type (double (*) (3) cannot be assigned to double (*) (9)

+7
source share
3 answers

While trying to figure out this problem, I got some results.

I found that the following statements do not cause compiler errors

 double arr[4][4][9]; double (*pp3)[9]; pp3 = arr[0]; 

So, is it right to infer from the above code that this pointer can be assigned to an array only if the number of elements it points to is equal to the number of smallest sizes of the array?

update: I think that a pointer can only be created on the smallest layer of an array.

Can someone explain this?

0
source

So, if you do:

 int i; double arr[4][3][3] = {{1,1,1,1,1,1,1,1,1},{2,2,2,2,2,2,2,2,2}, {3,3,3,3,3,3,3,3,3},{4,4,4,4,4,4,4,4,4}}; double (*pp3)[3][3]; pp3 = arr; for (i = 0; i <= 3; i++) { printf("pp3 + %d is %f \n", i, ***(pp3 + i)); } 

Then you will get the desired behavior. The problem with your code is that, as the compiler tells you, you are trying to assign a pointer to an array of 9 double ( double (*pp1)[sizeof(arr[0] / sizeof(arr[0][0][0])] evaluates to double (*pp1)[9] ), but you need a pointer to an array of 3 from array 3, which was declared using double arr[4][3][3] . From my tests, gcc will accept double (*pp1)[9] with a warning to the compiler, which I tried to get in my comment below. I hope this clears up.

If you want to keep this general, then you really need double (*pp3)[sizeof(arr[0]) / sizeof(arr[0][0])][sizeof(arr[0][0]) / sizeof(arr[0][0][0])] , which is a bloody nightmare.

EDIT: Forgot to dereference ... Had to copy / paste haha. An explanation of the behavior of the question code has also been added. Corrected in accordance with the comments.

+1
source

Why not just get the direction of the first element of this layer?

 double *pp1 = &ar[0][0][0]; double *pp2 = &ar[1][0][0]; /* and so on */ 
0
source

All Articles