I am trying to understand how 2D arrays are created in memory and I can not explain this weird behavior of pointers.
The following code:
int arr[4][3]={
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
int main(){
cout<<"&arr = "<<&arr<<endl;
cout<<" arr = "<<arr<<endl;
cout<<"*arr = "<<*arr<<endl;
cout<<"*(int*)arr = "<<*(int*)arr<<endl;
}
produces the output:
&arr = 0x8049bc0
arr = 0x8049bc0
*arr = 0x8049bc0
*(int*)arr = 1
Code: http://ideone.com/CzeVMu
arr
is "an array of arrays that decays into a pointer to an array" and *arr
(which is equivalent to arr[0]
) is an array.
Since the values of arr
and *arr
are the same, it means that the memory location that arr
points to is storing it's own address. But the memory location is actually storing the first element of the 2D array, which can be retrieved by first typecasting arr into int*
like this:*(int*)arr
. How is this possible?