A valid value for a pointer is null (it equals
0
), indicating that it points
to no object. Many of the standard header files define a
macro for a null pointer, NULL
, which many
programmers may prefer.
#include <stdlib.h> int *ip; ip = NULL;
It is permissible to use pointers as integer expressions treated as boolean expressions to detect a null pointer. (Null means ‘false’ in this context.) For example:
int *ip; if (ip) { /*ip
is not null. */ } if (!ip) { /*ip
is null. */ }
Direct comparisons are also possible (e.g. ip != NULL
).
If a pointer variable has not been given a value, it could be pointing anywhere, or be null. Its value is indeterminate. (Java refuses to compile programs that try to use indeterminate values.)
Do not dereference a null pointer.
Do not dereference an indeterminate
pointer. Unlike Java, where trying to access an
object through a null
reference will immediately raise a NullPointerException
,
dereferencing an invalid pointer in C could have any
effect! The program might fail immediately, or later, or
it might not appear to fail before it terminates
normally.