Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Pointers in 2D-arrays are confusing

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.

like image 423
HelloGoodbye Avatar asked Jan 27 '23 02:01

HelloGoodbye


1 Answers

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.

like image 94
Matthieu Brucher Avatar answered Feb 03 '23 19:02

Matthieu Brucher