Search code examples
c++cmultidimensional-arraypointer-arithmetic

why does this pointer arithmetic on a 2D array work?


I wrote the following code:

#include <iostream>
using namespace std;

int main()
{
    int a[10][10];
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            a[i][j] = i * j;
    cout << *(*(a + 3) + 4) << endl;
    return 0;
}

I was expecting it to print some garbage data, or a segmentation fault. What I got was 12. I tested it both in c and c++ (using gcc and g++ respectively), and I herd this works the same on VS although I haven't tested this. Why does this work, and is there a official documentation of this behavior?


Solution

  • When you want a simple answer build the complex type with typedefs

    it means:

    int a[10][10];
    

    will be:

    typedef int a10[10]; //a10 is array of 10 ints 
    a10 a[10]; //a is array of 10 a10s
    

    now to understand the sizes and position:

    sizeof(a) = 10 * 10 * sizeof int
    sizeof(a[0]) = is  10 * sizeof int
    a+1 is equal to &a[1]
    

    When you increment a pointer by 3 it is mean increment by sizeof of the type.

    address of a[1] == address of a[0] + sizeof(a[0])
    

    Therefore:

    *(*(a + 3) + 4) == a[3][4]