Can someone explain to me what is going on here? Consider the code
#include <iostream>
int main()
{
int A[2][2] = {{0}};
std::cout << A << std::endl; // First stdout line
std::cout << *A << std::endl; // Second stdout line
std::cout << *(*A) << std::endl; // Third stdout line
}
(Try the code here!)
It seems to me that A
should be an array of 2 pointers to arrays, each of which should contain 2 pointers to int
s. However, when running the code, the following is written to stdout:
0x7a665507cf80
0x7a665507cf80
0
To me, this makes it seem like the memory address of the first element in A
(printed on the first stdout line) is the same as the memory address of the first element in *A
. How is this possible, considering that A
and *A
are clearly two different arrays (since dereferencing A
and *A
gives different results)?
An alternative interpretation of the output is that the memory address 0x7a665507cf80
either contains the value 0x7a665507cf80
(i.e. a pointer located on that position—in this case A
—points to itself) or 0
, depending on if it is accessed from A
or *A
, which also doesn't really make sense to me.
int A[2][2] = {{0}};
This is a static 2D array, it's not a pointer to pointer, it's just a 1D array with special access.
The fact that it's not a point to pointer, but a 2D array on a 1D array means that A[0]
or *A
accesses the array and returns the 1D array that is the first row. Then the second dereferentiation gets the actual value. This generalizes to nD if you have int A[x][y][z][t]...
.
So the first two are the "same" address, but they are not the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With