388 Chapter 17 Miscellaneous and Advanced Features
struct entry
{
int value;
struct entry *next;
};
Here is a function called addEntrythat takes as its argument a pointer to the start of the
linked list and that adds a new entry to the end of the list.
#include <stdlib.h>
#include <stddef.h>
// add new entry to end of linked list
struct entry *addEntry (struct entry *listPtr)
{
// find the end of the list
while ( listPtr->next != NULL )
listPtr = listPtr->next;
// get storage for new entry
listPtr->next = (struct entry *) malloc (sizeof (struct entry));
// add null to the new end of the list
if ( listPtr->next != NULL )
(listPtr->next)->next = (struct entry *) NULL;
return listPtr->next;
}
If the allocation succeeds, a null pointer is placed in the nextmember of the newly allo-
cated linked-list entry (pointed to by listPtr->next).
The function returns a pointer to the new list entry, or the null pointer if the alloca-
tion fails (verify that this is, in fact, what happens). If you draw a picture of a linked list
and trace through the execution of addEntry, it will help you to understand how the
function works.
Another function, called realloc, is associated with dynamic memory allocation. It
can be used to shrink or expand the size of some previously allocated storage. For more
details, consult Appendix B.
This chapter concludes coverage of the features of the C language. In Chapter 18,
“Debugging Programs,” you learn some techniques that will help you to debug your C
programs. One involves using the preprocessor.The other involves the use of a special
tool, called an interactive debugger.