Roy Roy - 3 months ago 8
C++ Question

Confusion about pointer to an array

I have a very basic but haunting problem about pointer and array:

int main() {

int a[5] = { 1,2,3,4,5 };
int(*pa)[5] = &a;

std::cout << a << std::endl;
std::cout << &a << std::endl;

std::cout << pa << std::endl;
std::cout << (*pa) << std::endl;

return 0;
}


Surprisingly, all four outputs give the same address, something like
'006AF784'
, which means
a == &a
and
pa == *pa
. This does not make any sense to me!

I understand of course
'a'
is the pointer to the first element while
'&a'
is the pointer to the whole array, so
'a+1'
is different from
'&a+1'
. But a variable is equal to its address and a pointer is equal to the content which points to is not understandable to me. I wonder what is exactly going on within C and compiler.

Answer

Implicit conversion and "arrays decaying into pointers" is behind this.

Let's draw this array. Assume that it's stored beginning at address 0x98.

 +———————————————————+
 | 1 | 2 | 3 | 4 | 5 |
 +———————————————————+
 ^
 |
0x98

It should be clear that the address of the array is 0x98.
It's pretty clear that the address of its first element is also 0x98.

When you're printing

std::cout << a << std::endl;

a is converted into a pointer to its first element – it is equivalent to

std::cout << &a[0] << std::endl;

As illustrated above, this has the same numeric value as the pointer to the array.

Likewise, when you print

std::cout << (*pa) << std::endl;

*pa, being an array, is converted into a pointer to its first element.