Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
elyashiv Avatar asked May 10 '26 03:05

elyashiv


1 Answers

*(a + b)=a[b] you take the address of a, move it by b and take the value at the corresponding address

So *(*(a + 3) + 4)means *(a[3]+4) which mean a[3][4]=12

like image 163
slecorne Avatar answered May 12 '26 16:05

slecorne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!