3

I used to feel confused about these code

int a[3] = {1,2,3};
int b[2][3] = {...};
int (*p1)[3] = &a;  //pointer to array[3]
int (*p2)[3] = b; //same as above
int (*p3)[2][3] = &b; // pointer to array[2][3]

then I read some posts1 and understand the 'mystery' of array name including some explicit and implicit conversion.

So now I know p1 is a pointer to an array of 3 element with type int.

But how to understand that *(int (*)[3]) gets type int * or

*(int (*)[2][3] gets type int (*)[3] ?

Is it something that I should learn by rote?


posts I've read:

Is an array name a pointer?

Difference between `a` and `&a` in C++ where `a` is an array

Array to pointer decay and passing multidimensional arrays to functions


PS: I don't know if it's a stupid question. But after reading the posts I mentioned above. I still feel kinda weird about that dereference operation stuff. Maybe it's just how the languge syntax work which I should simply bear in mind and stop digging. :D
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Rick
  • 7,007
  • 2
  • 49
  • 79
  • In C++, it's best to avoid pointers and arrays as much as possible, but use containers and iterators. – Walter Apr 09 '18 at 10:17

1 Answers1

3

Firstly, you should understand array-to-pointer decay,

There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are

For example, a (int [3]) could decay to int *, b (int [2][3]) could decay to int (*)[3].

Then

how to understand that *(int (*)[3]) gets type int * or *(int (*)[2][3] gets type int (*)[3] ?

It depends on the context; more precisely, given p with type int (*)[3] (i.e. pointer to array), *p will get the array (int [3]), which could decay to int *.

Similarly, given p with type int (*)[2][3], *p will get the array int [2][3], which could decay to int (*)[3].

songyuanyao
  • 169,198
  • 16
  • 310
  • 405