Question about statically allocated 2D (or nD in general)

So if I declare a 2D array like int a[5][5] and I go into memory view I can see that a is not a vector of vectors (or pointer to pointer in other words), it is instead just one big vector (and the compiler knows that when you give it a[m][n] it just displays the (5*m + n)th element from the vector). This I already knew but I just wanted to confirm it.

But then we have this code:

1
2
3
4
5
int main()
{
	int a[5][5] = { 0 };
	cout << a + 5 << ", " << *(a + 5) << '\n';
}


And I find it very peculiar that it just prints the same things twice (it prints the starting address of a incremented by 5). But if *(a+5) prints out an address that means that a is indeed a pointer to pointer? Or it means that the C language represents a 2D array internally as a big vector but treats it as a vector of vectors?.. the second option sound more plausible but.. that means that the dereference operator, '*', is unreliable. Since *(a+5) does not return what is found at address a+5, but instead returns the address itself.

Can somebody explain to me what is going on here exactly? Any help is appreciated. Thanks in advance :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cassert>

int main()
{
    using element_type = int[5] ; // element_type is 'array of 5 int'
    typedef int element_type[5] ; // same as above

    element_type a[5] ; // type of a is 'array of 5 element_type'
    // int a[5][5] ; // same as above

    element_type* p = a ; // implicit conversion from array to pointer
                          // p is a pointer the first element_type in a
                          // p is a pointer to 'array of 5 int'

    ++p ; // increment p: p now points to the second  'array of 5 int'

    element_type* p2 = p+1 ; // p2 points to the third 'array of 5 int'

    int* pi = *p2 ; // *p2 is (reference to) 'array of 5 int'; implicit conversion from array to pointer
    // int *pi = *( a + 2 ) ; // same as above

    assert( pi == &( a[2][0] ) ) ;
    assert( (pi+2) == &( a[2][2] ) ) ;
    assert( (a+2) == &( a[2] ) ) ;
    assert( ( *(a+2) ) [2] == a[2][2] ) ;

}
Topic archived. No new replies allowed.