Prev NEXT

The Basics of C Programming

Pointers to Pointers

It is possible and often useful to create pointers to pointers. This technique is sometimes called a handle, and is useful in certain situations where the operating system wants to be able to move blocks of memory on the heap around at its discretion. The following example demonstrates a pointer to a pointer:

int **p;
	int *q;

	p = (int **)malloc(sizeof(int *));
	*p = (int *)malloc(sizeof(int));
	**p = 12;
	q = *p;
	printf("%d\n", *q);
	free(q);
	free(p);

Windows and the Mac OS use this structure to allow memory compaction on the heap. The program manages the pointer p, while the operating system manages the pointer *p. Because the OS manages *p, the block pointed to by *p (**p) can be moved, and *p can be changed to reflect the move without affecting the program using p. Pointers to pointers are also frequently used in C to handle pointer parameters in functions.

Advertisement

Pointers to Structures Containing Pointers

It is also possible to create pointers to structures that contain pointers. The following example uses the Addr record from the previous section:

typedef struct
	{
		char name[21];
		char city[21];
		char phone[21];
		char *comment;
	} Addr;
	Addr *s;
	char comm[100];

	s = (Addr *)malloc(sizeof(Addr));
	gets(s->name, 20);
	gets(s->city, 20);
	gets( s->phone, 20);
	gets(comm, 100);
	s->comment =
     (char *)malloc(sizeof(char[strlen(comm)+1]));
	strcpy(s->comment, comm);

The pointer s points to a structure that contains a pointer that points to a string.

In this example, it is very easy to create lost blocks if you aren't careful. For example, here is a different version of the AP example.

s = (Addr *)malloc(sizeof(Addr));
	gets(comm, 100);
	s->comment =
     (char *)malloc(sizeof(char[strlen(comm)+1]));
	strcpy(s->comment, comm);
	free(s);

This code creates a lost block because the structure containing the pointer pointing to the string is disposed of before the string block is disposed of, as shown here.

Linking

Finally, it is possible to create structures that are able to point to identical structures, and this capability can be used to link together a whole string of identical records in a structure called a linked list.

typedef struct
	{
		char name[21];
		char city[21];
		char state[21];
		Addr *next;
	} Addr;
	Addr *first;

The compiler will let you do this, and it can be used with a little experience to create structures like the one shown to the left.