This allows you to write loops which access the array elements in a sequence by
means of incrementing pointer — in the last iteration you will have a pointer
pointing to one element past an array, which is legal. However, applying the indi-
rection operator (
*
) to a “pointer to one past the last element” leads to undefined
behavior.
For example:
void
f (some_type a[],
int
n) {
/* function f handles elements of array a; */
/* array a has n elements of some_type */
int
i;
some_type *p = &a[0];
for
(i = 0; i < n; i++) {
/* .. here we do something with *p .. */
p++;
/* .. and with the last iteration p exceeds
the last element of array a */
}
/* at this point, *p is undefined! */
}
Pointer Subtraction
Similar to addition, you can use operators
-
,
--
, and
-=
to subtract an integral
value from a pointer.
Also, you may subtract two pointers. Difference will equal the distance between
the two pointed addresses, in bytes.
For example:
int
a[10];
int
*pi1 = &a[0], *pi2 = &[4];
i = pi2 - pi1;
// i equals 8
pi2 -= (i >> 1);
// pi2 = pi2 - 4: pi2 now points to a[0]
MikroElektronika: Development tools - Books - Compilers
73
page
mikroC - C Compiler for Microchip PIC microcontrollers
mikroC
making it simple...