Output of a
and &a
holds same value. But, they are different by type.
a reference to a
has type 'pointer to type
' but for &a
it is 'pointer-to-array-of-n-type
' where n
is the size of the array.
Lets try to understand the same in the below code:
#include <stdio.h>
int main()
{
int a[4]={1,2,3,4};
int *ptr1=a;
int (*ptr2)[4]=&a;
printf("a points to first element of array :%p\n",(void*)a);
printf("&a points to whole array. Start address is same as 'a': %p\n",(void*)&a);
printf("Incrementing 'a' steps to the next element in array New Value: %p\n",(void*)(a+1));
printf("Incrementing '&a' steps over the entire array. New Value: %p\n",(void*)(&a+1));
printf("ptr1: %p, ptr2:%p\n",(void*)ptr1,(void*)ptr2);
return 0;
}
Output:
a points to first element of array :0x7fff3da3d560
&a points to whole array. Start address is same as 'a': 0x7fff3da3d560
Incrementing 'a' steps to the next element in array New Value: 0x7fff3da3d564
Incrementing '&a' steps over the entire array. New Value: 0x7fff3da3d570
ptr1: 0x7fff3da3d560, ptr2:0x7fff3da3d560
ptr1
is of type: pointer to an integer. In this program, defined as pointer to array name. Hence, holds address of array's first element. ptr1 = &a[0]
ptr2
is of type: pointer to array of 4 ints. In this program, defined as pointer to the whole array. Incrementing ptr2
leads it to step over entire array. Generally useful only when operating with array of arrays.
Visualize storage of array a
:
+-----------------+-----------------+-----------------+-----------------+
| 1 | 2 | 3 | 4 |
+-----------------+-----------------+-----------------+-----------------+
0x7fff3da3d560 0x7fff3da3d564 0x7fff3da3d568 0x7fff3da3d56c 0x7fff3da3d570
▲ ▲ ▲ ▲ ▲ ▲ ▲ ▲
| | | | | | | |
|(a) | | (a + 1) | | |
| (ptr1) | (ptr1 + 1) | (ptr2 + 1)
|------------|----------------------------------------------------------|
| | |
| (ptr2) |
| |
(&a) = 0x7fff3da3d560 (&a + 1) = 0x7fff3da3d570