Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 415

81: } 15
82: }
83: } /* end of sort() */
84:
85: void print_strings(char *p[], int n)
86: {
87: int count;
88:
89: for (count = 0; count < n; count++)
90: printf(ā€œ%s\nā€, p[count]);
91: }
92:
93: int alpha(char *p1, char *p2)
94: /* Alphabetical comparison. */
95: {
96: return(strcmp(p2, p1));
97: }
98:
99: int reverse(char *p1, char *p2)
100: /* Reverse alphabetical comparison. */
101: {
102: return(strcmp(p1, p2));
103: }

Enter one line at time; enter a blank when done.
Roses are red
Violets are blue
C has been around,
But it is new to you!
Enter 0 for reverse order sort, 1 for alphabetical:
0
Violets are blue
Roses are red
C has been around,
But it is new to you!
Lines 32 and 33 in main()prompt the user for the desired sort order. The value
entered is placed in sort_type. This value is passed to the sort()function along
with the other information described for Listing 15.7. The sort()function contains a
couple of changes. Line 64 declares a pointer to a function called compare()that takes
two character pointers (strings) as arguments. Line 69 sets compare()equal to one of the
two new functions added to the listing based on the value of sort_type. The two new
functions are alpha()andreverse().alpha()uses the strcmp()library function just as
it was used in Listing 15.7; reverse()does not. reverse()switches the parameters
passed so that a reverse-order sort is done.

LISTING15.11 continued

INPUT/
OUTPUT

ANALYSIS

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

Free download pdf