4

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 ints. 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.

6
  • Compare typeid(A) with typeid(*A) - they will be different, since A and *A have different types, even if they have the same value Commented Nov 23, 2018 at 11:09
  • 1
    Arrays are not pointers, and pointers are not arrays. Commented Nov 23, 2018 at 11:22
  • @molbdnilo I know. Is that important in this case? Commented Nov 23, 2018 at 11:24
  • @HelloGoodbye If you know this, why do you believe that A "should be an array of 2 pointers to array, each of which should contain 2 pointers to ints"? Commented Nov 23, 2018 at 11:25
  • Same principle: if you look at any queue of people, you will notice that the beginning of the queue and the first person in the queue are in the same location, even though a queue and a person are totally different things. Commented Nov 23, 2018 at 11:30

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.