Comment

Part C — Command Line Parameters

created April 3, 2020


These puzzles discuss command line parameters. Command line parameters are how a program can easily be sent several parameters from the command line without the bother of implementing a user dialogue.

You have (presumably) been using command line parameters already in compiling and running programs from the command line. Here, for example, the program gcc has been supplied with several command line parameters:

C:\Source>gcc myProg.c -o myProg.exe

The file name myProg.c the flag -o and the output file myProg.exe are all command line parameters. It is convenient to have all this on one line rather than require several prompts and responses.

Your programs can use parameters from the command line. Say you have a program that processes an input file to produce an output file. With command line parameters, both file names can be given on the command line:

C:\Source>processData inputFile.txt resultFile.txt

Of course, the files names are different for different runs of your program.

Here is how this works. When the user enters the above command line, the operating system creates the following data structure. The operating system does this automatically for all programs whether they ask for it or not.

The variable argv points to an array of pointers to null-terminated strings. These are conceptually discrete strings, although they might be contiguous in memory.

The variable argc contains the number of arguments on the command line. In the above command line there are three parameters on the command line, counting the name of the executable itself: processData, inputFile.txt, and outputFile.txt.

(BUG NOTE: this is slightly different from what java does.)

The array is an array of pointers (addresses) to null-terminated strings. The last cell of the array is NULL (all zeros.)

(USAGE NOTE: on some systems the first string (pointed to by cell 0 of the array) is the complete path name of the program, not just what the user entered.

Question: What exactly is in the second cell of the array in the above picture?



Next Page         Home