User manual

Table Of Contents
mikroC PRO for PIC32
MikroElektronika
209
Pointer Addition
You can use operators +, ++, and += to add an integral value to a pointer. The result of addition is dened only if the
pointer points to an element of an array and if the result is a pointer pointing to the same array (or one element beyond
it).
If a pointer is declared to point to type, adding an integral value n to the pointer increments the pointer value by n *
sizeof(type) as long as the pointer remains within the legal range (rst element to one beyond the last element). If
type has a size of 10 bytes, then adding 5 to a pointer to type advances the pointer 50 bytes in memory. In case of
the void type, the size of a step is one byte.
For example:
int a[10]; /* array a containing 10 elements of type int */
int *pa = &a[0]; /* pa is pointer to int, pointing to a[0] */
*(pa + 3) = 6; /* pa+3 is a pointer pointing to a[3], so a[3] now equals 6 */
pa++; /* pa now points to the next element of array a: a[1] */
There is no such element as “one past the last element”, of course, but the pointer is allowed to assume such value. C
“guarantees” that the result of addition is dened even when pointing to one element past array. If P points to the last
array element, P + 1 is legal, but P + 2 is undened.
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 the pointer pointing to one element past the array, which is legal. However, applying an
indirection operator (*) to a “pointer to one past the last element” leads to undened behavior.
For example:
void f (some_type a[], int n) {
/* function f handles elements of array a; */
/* array a has n elements of type 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 undened! */
}