HP C A.06.05 Reference Manual

Expressions and Operators
Pointer Operators (*, ->, &)
Chapter 5 121
cc: "ptr_example3.c", line 9: warning 604: Pointers are not
assignment-compatible.
Pointer Arithmetic
The following arithmetic operations with pointers are legal:
You may add an integer to a pointer or subtract an integer from a pointer.
You may use a pointer as an operand to the ++ and operators.
You may subtract one pointer from another pointer, if they point to objects of the same
type.
You may compare two pointers
All other arithmetic operations with pointers are illegal.
When you add or subtract an integer to or from a pointer, the compiler automatically scales
the integer to the pointer's type. In this way, the integer always represents the number of
objects to jump, not the number of bytes. For example, consider the following program
fragment:
int x[10], *p1x = x, *p2x;
p2x = p1x + 3;
Since pointer p1x points to a variable (x) that is 4 bytes long, then the expression p1x + 3
actually increments p1x by 12 (4 * 3), rather than by 3.
It is legal to subtract one pointer value from another, provided that the pointers point to the
same type of object. This operation yields an integer value that represents the number of
objects between the two pointers. If the first pointer represents a lower address than the
second pointer, the result is negative. For example,
&a[3] - &a[0]
evaluates to 3, but
&a[0] - &a[3]
evaluates to -3.
It is also legal to subtract an integral value from a pointer value. This type of expression
yields a pointer value. The following examples illustrate some legal and illegal pointer
expressions:
long *p1, *p2;
int a[5], j;
char *p3;