# Exercise 2 - Command line arguments

    #include <iostream>
    #include <iomanip>
    #include <string>

    main(int argc, char *argv[])
    { int i;
      string *cmdline;

      cmdline = new string[argc];
      if (cmdline != NULL)
       { for (i = 0; i < argc; i++)
          cmdline[i] = argv[i];

         for (i = 0; i < argc; i++)
          cout << "cmd arg "
               << setw(4)
               << i << " is "
               << cmdline[i] << endl;
         delete[] cmdline;
         return 0;
       }
      else
       { cerr << "ERROR: no space."
              << endl;
         return -1;
       }
    }

You can see that I have added a variable of type pointer to a string:

      string *cmdline;

and I use the new operator to create an array of strings to hold the command line arguments.

Next I test the value return by the new operation to make sure that memory was allocated. If we received a result NULL then we should stop the program since it will be in an unsafe state. In small programs like this and in the environment you use at present it is unlikely that the machine will run out of memory. However you should ALWAYS check memory allocation when using dynamic variables.

Assuming that the creation of the string array was succesful we continue and the first for loop transfers the command line to the array of strings.

The second for loop just displays the strings.

Note that I use the delete operator to free the memory that was allocated by new. Get into the habit of doing this.

Return to lesson

Copyright © 1999 - 2001 David Beech