我永遠最愛伊茲娜 我永遠最愛伊茲娜 - 2 months ago 6
C++ Question

about the declaration of a mixture of array and pointer

May someone kindly explain the rules of declaring a mixture of array and pointer?

Below is what I have found. However, I do not understand why

int *p[10]
means
an allocation of 10 consecutive memory blocks (each can store data of type int *)
, while
int (*p)[10]
means
declaring a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
. What are the rules behind these codes?

int p[10]; //10 consecutive memory blocks (each can store data of type int) are allocated and named as p
int *p[10]; //10 consecutive memory blocks (each can store data of type int *) are allocated and named as p
int (*p)[10]; //p is a pointer to an array of 10 consecutive memory blocks (each can store data of type int)


Currently, my guess for the rules is:

xxx[10]
would be interpreted as
please allocating 10 memory blocks in which each blocks may store xxx
. Therefore,
int *p[10]
would be resulted in
10 memory blocks in which each can store data of type int *
;

(*p)
would be interpreted first due to
()
, and this would lead to a pointer pointing to somewhere. Therefore,
int (*p)[10]
would be resulted in
a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
.

Sorry for my bad English. Hopefully, you can understand what I mean.
Any help is appreciated! Thank you very much!

Answer

You actaully alread quoted the rules. The only thing to add is that you better write it like this:

int* p[10]; 
   ^------ belongs to int

int (*p)[10];
     ^---- belongs to p, ie p is pointer to int[10]

If you are unsure you can always check on http://cdecl.org/