In the following c/c++ code,
int main()
{
int a[3] = {11, 22, 33};
int *p[3];
p[0] = &a[0];
p[1] = &a[1];
p[2] = &a[2];
printf("(*p)[2] = %d\n",(*p)[2]);
printf("*(p[2]) = %d\n",*(p[2]));
return 0;
}
It turns out that (*p)[2] = *(p[2]) = a[2]
.
So, I understand that with int *p[3];
, I am creating an array of three pointers, and with the subsequent three lines after int *p[3];
, I am putting the address of a[0]
into p[0]
, address of a[1]
into p[1]
, and address of a[2]
into p[2]
.
Then, with *(p[2])
, I am retrieving the variable pointed by the address stored in p[2], which makes *(p[2]) = a[2]
. I have two questions regarding this simple code:
how to understand that
(*p)[2]
also equalsa[2]
?If p is no longer defined as an array of pointers to int variables, but an array of pointers to vectors of type int (
std::vector
in C++), does the equality(*p)[2] = *(p[2])
still hold?