I'm having a problem using malloc() to allocate memory for words from a text file. I need to modify the code below by reading words from the words.txt file and allocate only the amount of memory necessary for each word using malloc().

Then, I need to sort the words in length order of the word with the longest length words being the lowest index in the array. If two or more words are the same length, they are then sorted by ASCII sequence.

The code below stores the words from a text file in a 2D array and simply lists the words after they have been read in from the file. It needs to be modified (changed) so that the words are read using the dynamic memory function malloc(). I take the number of words in the data file (in the attached file there are 22 words) and I need to allocate memory to store each word using a dynamic memory array for the words. In addition to that, each word should have memory allocated by allocating only enough memory for each word as it is read from the file using malloc().

For example: "another" should only require 8 bytes to be stored and "yesterday" would only require 10 bytes to be stored.

Here is the code that needs to be modified so that the words are read using malloc() to allocate memory and sort the words:


Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXWORDS       500
#define MAXWORDLENGTH  20

int main(int argc, char *argv[]) {
    char words[MAXWORDS][MAXWORDLENGTH];
    int i;
    if (argc == 2)
    {
        int iNumWords = readwords(argv[1], words);
        for (i=0; i<iNumWords; i++)
            printf ("%s\n", words[i]);
        printf("\nThe total number of words in %s is %d", argv[1],  
        iNumWords);
    }

    system("PAUSE");
    return 0;
}

/* Function to read words into a two-dimensional array */

int readwords(char *filename, char words[][MAXWORDLENGTH])
{
   int   iCount = 0;
   FILE *fp = fopen(filename, "r");   // Open file for reading

   while (!feof(fp))
      fgets(words[iCount++], MAXWORDLENGTH, fp);

   fclose(fp);
   return iCount-1;
}
I need to modify this code so that each word of the text file is allocated only the amount of memory necessary for each word using the malloc() function. After that, the words need to be sorted in order of length. I'm not quite sure how to do that but I'm thinking I need to use the qsort() function but I would like confirmation of that from someone who knows for sure.

Any help, advice or suggestions would be greatly appreciated.

Thanks. I have included an attachment of the "words.txt" file for reference.