tags:

views:

58

answers:

2

Please look at this peice of code :-

#include<stdio.h>
int main()
{
int arr[2][2]={1,2,3,4};
printf("%d %u %u",**arr,*arr,arr);
return 0;
}

When i compiled and executed this program i got same value for arr and *arr which is the starting address of the 2 d array. For example:- 1 3214506 3214506

My question is why does dereferencing arr ( *arr ) does not print the value stored at the address contained in arr ?

+4  A: 

*arr is type integer array of length 2, so it shares the same address as arr. They both point to the beginning of their arrays, which is the same location.

WhirlWind
A: 

in C, a 2d array is not represented in memory as an array of arrays; rather, it is a regular 1d array, in which the first given dimension is needed in order to calculate the right offset within the array at execution time. This is why in a multi-dimensional array you always need to specify all the dimensions except the last one (which is not required); for example, if you declare an array like

int a[2][3][4];

the array would be represented in memory as a single array of 2*3*4 elements in total. Trying to access the element at position (i,j,k), will actually be translated into accessing the element 3*i+4*j+k in the plain array. In some sense, the initial dimensions are needed to know where to put "row breaks" in the 1d array.

tiziano88