Homework 5

CS18

50 pts., due Apr. 29

This is an exercise in dynamic memory allocation, pointers ( char*), and pointers to pointers ( char**).

You are given (actually, make up a file containing people's names) a data file in the following format:

n
name 1
name 2
...
name n
I.e., the file consists of n names, with n's value given on the first line of the file.

Sort the names and write them to an output file. There are a few restrictions on how you may store your data:

Here's non-modular pseudocode for the program (which should itself be modular):

char** names;
char buffer[NAME_LEN];

open the input data file
read the number of names (n)
allocate n char*'s; store starting address in names

for i := 0 to n - 1
   read the next name into buffer
   allocate space for the name and the terminating '\0'; store
      starting address in names[i]
   copy the name to the allocated space
end_for

close the input data file

sort the names

open the output data file
write the names in sorted order
close the output data file

deallocate the space for each of the names
deallocate the space pointed to by names

Command line arguments are available to the program through main's formal parameters argc and argv. The former is an int which is a count of the total number of ``words'' on the command line (the command itself counts as one word). The latter is an array of char*'s, each pointing to a different command line word. argv[0] is the command, argv[1] is the first command line argument, etc.

If n command line arguments are expected, the program is expected to verify that exactly that many arguments passed. Here is an example program fragment:

int main(int argc, char* argv[])
{
   // Arbitrarily expect two arguments.
   if (argc != 3)
   {
      cout << "Two arguments expected.\n";
      return 1;
   }

   // Print each of the arguments on a line by itself.
   for (int i = 1; i < argc; ++i)
      cout << argv[i] << endl;

   return 0;
}



Thomas P. Kelliher
Sun Apr 21 15:47:46 EDT 1996
Tom Kelliher