CS 262
Program 3
due November 11, 2011

The program

Your program will ask the user to enter words and display the entered words sorted two ways. The program will first ask the user how many words he or she wishes to enter, then accepts that many words. The words will then be displayed sorted in lexicographical order and then displayed in order sorted by word length. Running the program may show something like:


How many words?  9
->  the
->  quick
->  brown
->  fox
->  jumps
->  over
->  the
->  lazy
->  dog

lexicographic order:
brown
dog
fox
jumps
lazy
over
quick
the
the

by length:
dog
fox
the
the
lazy
over
brown
jumps
quick

Internals

Your program will create, using malloc(), an array of strings. This, of course, will be an array of (char *) and each position in the array will point to a char array holding the string. After the user has chosen the number of words to be entered, say word_count, you will allocate an array holding word_count pointers:


char **words = malloc(word_count*sizeof(char *));
Accept the words (using scanf()) and after each word has been entered the program will allocate exactly enough memory to hold the string, copy the string to this allocated memory, and store it in the proper place in the array.

To sort the array use the qsort() function from the library (remember to #include <stdlib.h>). The (rather ugly) prototype for qsort() is:


void qsort(void *base, int number_of_elts, int size_of_elt, int *compare_fcn(const void *, const void *));
Here base is the base address of the array to be sorted (words), number_of_elts is the number of elements to be sorted, size_of_elt is the size of an element of the array (sizeof(char *) for us), and compare_fcn is the name of a function which will compare two elements of the array.

You will need two compare functions, one to compare for lexicographical order and one to compare for length. You may use the following two functions:


int new_strcmp(const void *a, const void *b)
{
   return strcmp(*(char **)a, *(char **)b);
}

int length_cmp(const void* a, const void *b)
{
   return strlen(*(char **)a) - strlen(*(char **)b);
}

To turn in

You will turn in your source code and a terminal session using the following sample input words:


Four score and seven or maybe eight years ago I lost count