Monday 7 November 2011

Using a Null Pointer As a Sentinel Value in C programming

Using a Null Pointer As a Sentinel Value

The third way a null pointer can be used is as a “sentinel” value. A sentinel value is a special value that marks
the end of something. For example, in main(), argv is an array of pointers. The last element in the array
(argv[argc]) is always a null pointer. That’s a good way to run quickly through all the elements:
/*
A simple program that prints all its arguments.
It doesn’t use argc (“argument count”); instead,
it takes advantage of the fact that the last
value in argv (“argument vector”) is a null pointer.
*/
#include <stdio.h>
#include <assert.h>
int
main( int argc, char **argv)
{
int i;
printf(“program name = \”%s\”\n”, argv[0]);
for (i=1; argv[i] != NULL; ++i)
printf(“argv[%d] = \”%s\”\n”,
i, argv[i]);
assert(i == argc); /* see FAQ XI.5 */
return 0; /* see FAQ XVI.4 */
}

Cross Reference:

VII.3: What is a null pointer?
VII.10: Is NULL always equal to 0?
XX.2: Should programs always assume that command-line parameters can be used?

No comments:

Post a Comment