With the following code, two different addresses are printed out. Can anyone explain why? I'm not the most proficient with pointers but I presumed that they would give the same address.
#include <iostream>
int main() {
float (*arrayName)[2][4][4];
auto address1 = (**arrayName)[1]; // 0x10
auto address2 = (*arrayName)[1][0]; // 0x40
std::cout << "Address1: " << address1 << std::endl;
std::cout << "Address2: " << address2 << std::endl;
}
0x40 is the address I'm looking for. Just don't understand why I get two different answers.
I was expecting both to give me an answer of 0x40 however one doesn't. Tried this code on an online C++ compiler and both gave me the address of 0x10. However on my development RHEL7 vm, I get 0x10 and the expected 0x40 address.
As for what's really going on, please learn that for any pointer or array p
and index i
, the expression p[i]
is exactly equal to *(p + i)
.
From that it follows that p[0]
must be equal to *(p + 0)
which of course is equal to *(p)
which is the same as *p
.
And from that we can learn that *arrayName
is the same as arrayName[0]
, from which follows that **arrayName
is arrayName[0][0]
.
With this information it's easy to see that (*arrayName)[1][0]
is different from (**arrayName)[1]
:
(*arrayName)[1][0]
is the same as arrayName[0][1][0]
.
(**arrayName)[1]
is the same as arrayName[0][0][1]
.
But remember, because arrayName
isn't assigned or initialized with a specific pointer, it can't be dereferenced.