The C standard library includes two functions that make use of a function pointer to provide
flexible sort (qsort()) and binary search (bsearch()) capabilities. We are going to use those
functions, along with malloc() and free(), which provide support for allocating blocks of
dynamic memory. Consider a program that sorts a series of words entered by a user:
Enter word: foo
Enter word: bar
Enter word: baz
Enter word: quux
Enter word:
In sorted order: bar baz foo quux
a. (30 pts) Write a program that reads in words from stdin and prints them to stdout in
sorted order. Your program must have the following constraints and assumptions:
• Assume that each word is no more than 20 characters long.
• Stop reading words when the user enters and empty word (only a \n).
• Use malloc() to store each word in a dynamically allocated string.
• Hold the string addresses returned by malloc() in an array of pointers to keep
track of the strings.
•
After all the words have been entered, sort the array using the C library qsort()
function. The compare function is included in the starters folder.
•
Use a loop to print the words in sorted order.
• Don't forget to use free() to deallocate the strings before you exit the program.
• Hint: This is not required, but you may want to use the getaline() (and perhaps
the copy()) function(s) from the LongestLineHelper ADT used in Homeworks #1
and #2. Longest LineHelper.o is included in the starters folder.
Note: The intent is that you only use the provided API which is the same as in
LongestLineHelper.c but you won't be marked down if you make changes to the
functions.
b. (5 pts) Compile, debug, and execute your application using the command line. Include at
least 10 words to show that your application works correctly. Submit your source code and
a transcript showing that your application runs successfully.
Fig: 1