Is 2d array a double pointer?
No. This line of your program is incorrect:
int **ptr = (int**)matrix;
This answer deals with the same topic
If you want concrete image how multidimensional arrays are implemented:
The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:
matrix: 11 22 33 99 44 55 66 110
----------- the first element of matrix
------------ the second element of matrix
Therefore, to address element matrix[x][y]
, you take the base address of matrix + x*4 + y
(4 is the inner array size).
When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]
. The 4
in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y]
, you get matrix_ptr + x*4 + y
, which is exactly the same as above.
The cast ptr=(int**)matrix
is therefore incorrect. For once, *ptr
would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1]
anywhere in the memory of the program.
Note: the calculations in this post assume sizeof(int)==1
, to avoid unnecessary complexity.