Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 401

15


Pulling Things Together With an Example ..................................................

Now it’s time for a more complicated example. Listing 15.7 uses many of the program-
ming skills you’ve learned, including arrays of pointers. This program accepts lines of
input from the keyboard, allocating space for each line as it is entered and keeping track
of the lines by means of an array of pointers to type char. When you signal the end of an
entry by entering a blank line, the program sorts the strings alphabetically and displays
them on-screen.
If you were writing this program from scratch, you would approach the design of this
program from a structured programming perspective. First, make a list of the things the
program must do:


  1. Accept lines of input from the keyboard one at a time until a blank line is entered.

  2. Sort the lines of text into alphabetical order.

  3. Display the sorted lines on-screen.
    This list suggests that the program should have at least three functions: one to accept
    input, one to sort the lines, and one to display the lines. Now you can design each func-
    tion independently. What do you need the input function—called get_lines()—to do?
    Again, make a list:

  4. Keep track of the number of lines entered, and return that value to the calling pro-
    gram after all lines have been entered.

  5. Don’t allow input of more than a preset maximum number of lines.

  6. Allocate storage space for each line.

  7. Keep track of all lines by storing pointers to strings in an array.

  8. Return to the calling program when a blank line is entered.
    Now think about the second function, the one that sorts the lines. It could be called
    sort(). (Really original, right?) The sort technique used is a simple, brute-force method
    that compares adjacent strings and swaps them if the second string is less than the first
    string. More exactly, the function compares the two strings whose pointers are adjacent
    in the array of pointers and swaps the two pointers if necessary.
    To be sure that the sorting is complete, you must go through the array from start to fin-
    ish, comparing each pair of strings and swapping if necessary. For an array of nele-
    ments, you must go through the array n–1 times. Why is this necessary?
    Each time you go through the array, a given element can be shifted by, at most, one posi-
    tion. For example, if the string that should be first is actually in the last position, the first
    pass through the array moves it to the next-to-last position, the second pass through the


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

Free download pdf