Monday 7 November 2011

Using a Null Pointer to Stop Indirection or Recursion in C programming

Using a Null Pointer to Stop Indirection or Recursion

Recursion is when one thing is defined in terms of itself. A recursive function calls itself. The following
factorial function calls itself and therefore is considered recursive:

/* 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;
};

There are also doubly linked lists (which also have a pointer to the preceding element) and trees and hash
tables and lots of other neat stuff. You’ll find them described in any good book on data structures.

You refer to a linked list with a pointer to its first element. That’s where the list starts; where does it stop?
This is where the null pointer comes in. In the last element in the list, the next field is set to NULL when there
is no following element. To visit all the elements in a list, start at the beginning and go indirect on the next
pointer as long as it’s not null:
while ( p != NULL )
{
/* do something with p->str */
p = p->next;
}

Notice that this technique works even if p starts as the null pointer

No comments:

Post a Comment