Back to DFS's C Page


OAC Problem Set VIII

Dynamic Memory Allocation #2

Sorting Structures Using a Linked List

The programs you wrote for Problem Set VII, even though they utilized dynamic memory allocation, had one major shortcoming; you had to establish an array in which to hold the pointers to the memory allocated. This meant that you had to allow for a maximum number of pointers for the structures that were to be used.

There are many occasions in programming when we as programmers have no idea how much data our programs will be asked to handle or how much RAM the machine our program is running on might have (or how much is still available to us because other programs are running). Linked lists of data allow us to use as little or as much memory as necessary (as long as it is available).

Before attempting this problem, read the Dynamic Memory Allocation page. Then save, compile, and trace through the sample program, making sure you understand how the pointers are used.

For the programs below, you are to use the data from Section 69 of Premru's book which I have placed in its entirety on a web site.


Program I: Reading Data, Sorting & Writing to a File

Using the following global struct declaration

struct record_s {
   char *english,
        *italian,
        *german,
        *slovenian;
   struct record_s *nx; }; 

and these variable declarations in main()

struct record_s *head_record_ptr = NULL;
struct record_s *current_record_ptr = NULL;

you are to write a program which reads in the data from Section 69 of Premru's book, sorts it based on the English and writes it out to a file called premru69.eng.

N.B. The data in premru69.dat is encoded in Latin-2 (ISO-8859-2).


B O N U S

Program II: Reading, Multiple Sorting, Printing a Table & Writing to a File

Using the declarations given above, cannibalize your source code for Program I and add the following features:

Your program must follow the pseudocode provided below.

  1. Open a file using a command-line argument
  2. Call a function to read in language info using a loop
    1. Get memory allocated, adding the structure to the linked list
    2. Read language data into allocated memory
    3. Increment counter
  3. Close file
  4. Using a loop and a switch
    1. Print out a labeled table of the first ten records of data
    2. Display the sort options available
    3. Get the user's choice
    4. Call a function to sort the data if requested to do so
  5. Call a function to save the last version of the data to premru69sorted.dat
  6. Call a function to free memory used for language data structures

N.B. A graceful exit from the program is required if the user-specified file does not exist. For this program, you must ensure that the memory requested is in fact allocated -- if it is not, you must call the function described in Step 7 before exiting.


Created 27 Feb 00
© DFStermole 2000