null pointer in c

Levels of difficulty: / perform operation:

There are times when it’s necessary to have a pointer that doesn’t point to anything. The macro NULL, defined in , has a value that’s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL.

You can’t use an integer when a pointer is required. The exception is that a literal zero value can be used as the null pointer. (It doesn’t have to be a literal zero, but that’s the only useful case. Any expression that can be evaluated at compile time, and that is zero, will do. It’s not good enough to have an integer variable that might be zero at runtime.)

pointers Program

/* Dumb implementation; should use a loop */
unsigned factorial( unsigned i ) {
	if ( i == 0 || i == 1 ) {
		return 1;
	} else {
		return i * factorial( i - 1 );

A recursive data structure is defined in terms of itself. The simplest and most common case is a (singularly) linked list. Each element of the list has some value, and a pointer to the next element in the list:

struct string_list
     char    *str;   /* string (in this case) */
     struct string_list      *next;
while ( p != NULL )
     /* do something with p->str */
     p = p->next;

Using a Null Pointer As a Sentinel Value

/* 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. */
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);
	return 0;