We can use the ARGV.C program to illustrate another handy property of
pointers: null pointers. Consider this modification (ARGV1.C):
/* ARGV1.C: Demonstrate null pointers. */
#include <stdio.h>
void show_args( char *argument );
int main( int argc, char **argv )
{
while( *argv )
show_args( *(argv++) );
return 0;
}
void show_args( char *argument )
{
printf( "%s\n", argument );
}
The ARGV1.C program gives the same output as the previous program but it uses a while loop instead of a for loop. The test expression in this loop,
while( *argv )
is equivalent to this test expression:
while( *argv != 0 )
The loop in ARGV1.C continues until it finds a “null pointer,” a pointer that contains 0. In this case, the null pointer means we have reached the end of the array: no more strings are available.
Summary: Null pointers can be used to show success or failure and as markers in a series.
Many C library functions use null pointers to signal the success or failure of an operation that returns a pointer. For instance, the library function malloc normally returns a pointer to the beginning address of the memory area it allocates. If no memory is available, malloc returns a null pointer to show the operation failed. Similarly, the fopen function usually returns a pointer to a FILE structure, but returns a null pointer when it fails.
Null pointers can also be used to mark the end of a list of pointers, such as the argv array or a linked list.