HP C A.06.05 Reference Manual

Expressions and Operators
Pointer Operators (*, ->, &)
Chapter 5122
p1 = a; /* Same as p1 = &a[0] */
p2 = p1 + 4; /* legal */
j = p2 - p1; /* legal -- j is assigned 4 */
j = p1 - p2; /* legal -- j is assigned -4 */
p1 = p2 - 2; /* legal -- p2 points to a[2] */
p3 = p1 - 1; /* ILLEGAL -- different pointer types*/
j = p1 - p3; /* ILLEGAL -- different pointer types*/
j = p1 + p2; /* ILLEGAL -- cannot add pointers */
Arrays and Pointers
Arrays and pointers have a close relationship in the C language. You can exploit this
relationship in order to write more efficient code. See the discussion of “Array Subscripting ([
])” on page 86 for more information.
Casting a Pointer's Type
A pointer to one type may be cast to a pointer to any other type. For example, in the following
statements, a pointer to an int is cast to a pointer to a char. Presumably, the function func()
expects a pointer to a char, not a pointer to an int.
int i, *p = &i;
func((char *) p);
As a second example, a pointer to a char is cast to a pointer to struct H:
struct H {
int q;
} x, y;
char *genp = &x;
y = (struct H *)genp->q;
See “Cast Operator” on page 98 for more information about the cast operator.
It is always legal to assign any pointer type to a generic pointer, and vice versa, without a
cast. For example:
float x, *fp = &x;
int j, *pj = &j;
void *pv;
pv = fp; /* legal */
fp = pv; /* legal */
In both these cases, the pointers are implicitly cast to the target type before being assigned.