Why doesn't int** ptr point to the same address as int arr[3][3] when accessing ptr[i][j]?

c++, pointers

Solution

`int **ptr` and an `int arr[3][3]` are different, since:

 -----------------------------------
|    C    |         Maths           |
 -----------------------------------
| ptr + 1 | ptr + sizeof(int*)      |
 -----------------------------------
| arr + 1 | arr + 3 * sizeof(int*)  |
 -----------------------------------

So you won't get the same results at all (moreover, `ptr` and `arr` may not have the same memory representation).

int (*ptr)[3] = arr;

will work, since only the first dimension of `arr` decays to a pointer.

Problem

I was answering this question but when I tested the following code I got confused. ``` #include <iostream> using namespace std; int main() { int **ptr; int arr[3][3]; ptr =(int **) arr; for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ cout << &arr[i][j] << " =? "; cout << &(ptr[i][j]) << endl; } } return 0; } ``` But I get this ouput: ``` 0x7fff5700279c =? 0 0x7fff570027a0 =? 0x4 0x7fff570027a4 =? 0x8 0x7fff570027a8 =? 0 0x7fff570027ac =? 0x4 0x7fff570027b0 =? 0x8 0x7fff570027b4 =? 0 0x7fff570027b8 =? 0x4 0x7fff570027bc =? 0x8 ``` Why aren't they the same?

Original source

Related problems