The name of an array, except in expressions such as
sizeof my_arr
and
&my_arr
, yields the address of
its first element, so my_arr ==
&my_arr[0]
, and my_arr + 3 ==
&my_arr[3]
. It is said that the array name
decays into a pointer to its first element.
The construct []
is in fact a
binary
operator. One of its operands must be an object
pointer, and the other an integer, and it simply adds them
together, regardless of order, then dereferences. This means that the two
expressions my_addr[3]
and
3[my_addr]
are equivalent!
Given the addresses of two elements of the same array, the address of one can be subtracted from the address of the other, yielding the difference of their indices:
int my_arr[10]; assert(&my_arr[6] - &my_arr[4] == 2);
The result is of a signed integer type called
ptrdiff_t
, defined in <stddef.h>
, and having
the range from PTRDIFF_
to PTRDIFF_
,
which is at least ±65535. Use the type modifier
t on integer conversion specifiers with
printf
and scanf
to convert a
ptrdiff_t
to and from characters (for
example, "%td"
).
atomic_
is an alias for _Atomic
ptrdiff_t
.