int main()
{
matrix[2][4] = {{11,22,33,99},{44,55,66,110}};
int **ptr = (int**)matrix;
printf("%d%d",**matrix,*ptr);
}
But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] ..
what type does the compiler store this array as… is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.
No. This line of your program is incorrect:
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:
Therefore, to address element
matrix[x][y], you takethe 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]. The4in 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 formatrix_ptr[x][y], you getmatrix_ptr + x*4 + y, which is exactly the same as above.The cast
ptr=(int**)matrixis therefore incorrect. For once,*ptrwould mean a pointer value stored at address of matrix, but there isn’t any. Secondly, There isn’t a pointer tomatrix[1]anywhere in the memory of the program.Note: the calculations in this post assume
sizeof(int)==1, to avoid unnecessary complexity.