Datasheet
Two pointers pointing to the same array may be compared by using relational oper-
ators ==, !=, <, <=, >, and >=. Results of these operations are the same as if
they were used on subscript values of array elements in question:
int *pa = &a[4], *pb = &a[2];
if (pa == pb) {... /* won't be executed as 4 is not equal to 2 */ }
if (pa > pb) {... /* will be executed as 4 is greater than 2 */ }
You can also compare pointers to zero value – testing in that way if the pointer actu-
ally points to anything. All pointers can be successfully tested for equality or inequal-
ity to null:
if (pa == 0) { ... }
if (pb != 0) { ... }
Note: Comparing pointers pointing to different objects/arrays can be performed at
programmer’s own responsibility — a precise overview of data’s physical storage is
required.
Pointer Addition
You can use operators +, ++, and += to add an integral value to a pointer. The
result of addition is defined 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 (first 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 defined
even when pointing to one element past array. If P points to the last array element,
P + 1 is legal, but P + 2 is undefined.
163
MIKROELEKTRONIKA - SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
Language Reference
mikroC PRO for AVR
CHAPTER 5