Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 405

15


After execution returns from get_lines()tomain(), the following has been accom-
plished (assuming that a memory allocation error didn’t occur):


  • A number of lines of text have been read from the keyboard and stored in memory
    as null-terminated strings.

  • The array lines[]contains pointers to all the strings. The order of pointers in the
    array is the order in which the strings were input.

  • The variable number_of_linesholds the number of lines that were input.
    Now it’s time to sort. Remember, you’re not actually going to move the strings around,
    only the order of the pointers in the array lines[]. Look at the code in the function
    sort(). It contains one forloop nested inside another (lines 57 through 68). The outer
    loop executes number_of_lines - 1times. Each time the outer loop executes, the inner
    loop steps through the array of pointers, comparing (string n)with(string n+1)for
    n = 0ton = number_of_lines - 1. The comparison is performed by the library func-
    tionstrcmp()on line 61, which is passed pointers to two strings. The function strcmp()
    returns one of the following:

  • A value greater than zero if the first string is greater than the second string.

  • Zero if the two strings are identical.

  • A value less than zero if the second string is greater than the first string.
    In the program, a return value from strcmp()that is greater than zero means that the
    first string is “greater than” the second string, and they must be swapped (that is, their
    pointers in lines[]must be swapped). This is done using a temporary variable tmp.
    Lines 63 through 65 perform the swap.
    When program execution returns from sort(), the pointers in lines[]are ordered prop-
    erly: A pointer to the “lowest” string is in lines[0], a pointer to the “next-lowest” is in
    lines[1], and so on. Suppose, for example, that you entered the following five lines, in
    this order:
    dog
    apple
    zoo
    program
    merry
    The situation before calling sort()is illustrated in Figure 15.5, and the situation after
    the return from sort()is illustrated in Figure 15.6.
    Finally, the program calls the function print_strings()to display the sorted list of
    strings on-screen. This function should be familiar to you from previous examples in this
    chapter.


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

Free download pdf