HP C A.06.05 Reference Manual

Expressions and Operators
Pointer Operators (*, ->, &)
Chapter 5 123
Null Pointers
The C language supports the notion of a null pointer — that is, a pointer that is guaranteed
not to point to a valid object. A null pointer is any pointer assigned the integral value 0. For
example:
char *p;
p = 0; /* make p a null pointer */
In this one case — assignment of 0 — you do not need to cast the integral expression to the
pointer type.
Null pointers are particularly useful in control-flow statements, since the zero-valued pointer
evaluates to false, whereas all other pointer values evaluate to true. For example, the
following while loop continues iterating until p is a null pointer:
char *p;
. . .
while (p) {
. . .
/* iterate until p is a null pointer */
. . .
}
This use of null pointers is particularly prevalent in applications that use arrays of pointers.
The compiler does not prevent you from attempting to dereference a null pointer; however,
doing so may trigger a run-time access violation. Therefore, if it is possible that a pointer
variable is a null pointer, you should make some sort of test like the following when
dereferencing it:
if (px && *px) /* if px = 0, expression will short-circuit
. . . before dereferencing occurs*/
Null pointers are a portable feature.
Example 5-1 Accessing a 1-Dimensional Array Through Pointers
/* Program name is "pointer_array_example1". This program
* shows how to access a 1-dimensional array through
* pointers. Function count_chars returns the number of
* characters in the string passed to it.
* Note that *arg is equivalent to a_word[0];
* arg + 1 is equivalent to a_word[1]...
*/
#include <stdio.h>
int count_chars(char *arg)