In the code below, I declare an int array "a" and then a pointer to the entire array "ap":
int main(){
int a[3] = {10, 100, 1000};
int (*ap)[] = &a;
printf("%p\n", ap);
printf("%p\n", *ap);
printf("%d\n", **ap);
return 0;
}
The first print of ap shows that it is actually a pointer to the first value of the array. OK.
But in the second print, ap is dereferenced and, yet, the value is the same: pointer to the first value of the array.
It's only after a "double dereferencing" that I get the value of the first array element (10 in my example):
0x7fff193310cc
0x7fff193310cc
10
Why is that so?
Thanks a lot!
When you do *ap
it's basically the same as doing *(&a)
, which is in essence plain a
.
And as arrays decays to pointers to their first elements, plain a
is the same as &a[0]
.
Now here's the interesting thing: The location of the array a
and the location of the first element of a
is the exact same location.
It's easy to see if we draw it out:
+------+------+------+ | a[0] | a[1] | a[2] | +------+------+------+ ^ | &a[0] | &a
See how both &a[0]
and &a
are pointing to the same location?
But also remember that while both &a[0]
and &a
are pointing to the same location, they have very different types:
&a[0]
will have the type int *
&a
will have the type int (*)[3]