Sams Teach Yourself C in 21 Days

(singke) #1
Notice that malloc()is used to allocate the memory for the new element. As each new
element is added, only the memory needed for it is allocated. The calloc()function
could also be used. You should be aware of the differences between these two functions.
The main difference is that calloc()will initialize the new element; malloc()will not.

420 Day 15

In these code fragments, the return value of malloc()is not checked to
ensure that the memory was successfully allocated. In a real program, you
should always check the return value of a memory allocation function.

Caution


You should always initialize pointers to NULLwhen you declare them. Never
Tip leave a pointer uninitialized. Doing so is just asking for trouble.

Adding an Element to the End of the List
To add an element to the end of a linked list, you start at the head pointer and go through
the list until you find the last element. After you’ve found it, follow these steps:


  1. Create an instance of your structure, allocating memory space using malloc().

  2. Set the next pointer in the last element to point to the new element (whose address
    is returned by malloc()).

  3. Set the next pointer in the new element to NULLto signal that it is the last item in
    the list.
    Here is the code:
    person current;
    ...
    current = head;
    while (current->next != NULL)
    current = current->next;
    new = (person
    )malloc(sizeof(struct person));
    current->next = new;
    new->next = NULL;
    Figure 15.11 illustrates the procedure for adding a new element to the end of a linked
    list.


25 448201x-CH15 8/13/02 11:13 AM Page 420

Free download pdf