Does &arr
something point to the first address of the array?
&arr
is pointer to whole array of 10
integers and not the pointer to first element of the array.
Is b=&arr;
true?
No, given int *b
, then b=&arr;
is an incompatible pointer type assignment because the type of &arr
is int (*)[10]
whereas the type of b
is int *
. (If the definition is int (*b)[10]
, there is no problem.)
what is the difference between arr
and &arr
?
The arr
, when used in a statement, will be converted to pointer to first element of array (there are few exceptions to this rule). The type of arr
is int *
and it is equivalent to &arr[0]
1) (i.e. both are pointer to first element of array).
The &arr
is pointer to the whole array (it's type is int (*)[10]
).
The address of an array (&arr
) and address of first element of an array (arr
or &arr[0]
) is numerically same though their type is different. That means, if we add 1
to them there results will be different (provided that the array size is greater than 1
). arr + 1
result in pointer to 2
nd element whereas &arr + 1
result in pointer after 10
elements of array arr
.
Demonstration:
#include<stdio.h>
int main (void) {
int arr[10];
printf ("arr - %p\n", (void *)arr);
printf ("&arr - %p\n", (void *)&arr);
printf ("arr + 1 - %p\n", (void *)(arr + 1));
printf ("&arr + 1 - %p\n", (void *)(&arr + 1));
return 0;
}
Output:
# ./a.out
arr - 0x7ff7bec77950
&arr - 0x7ff7bec77950
arr + 1 - 0x7ff7bec77954
&arr + 1 - 0x7ff7bec77978
Also, when using the format specifier %p
in printf()
, the corresponding argument('s) should be type casted to (void *)
.
1). From C11 Standards#6.5.2.1
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))..
Hence,
arr -> (arr + 0) -> &( *(arr + 0) ) -> &arr[0]