Home Segments Index Top Previous Next

595: Mainline

Most programmers prefer to have their programs take a file name as a command-line argument, rather than via a scanf statement.

To handle command line arguments, you need to know that C allows you to include two parameters in the main function. If you include those two parameters, then the value of the first parameter is the number of white space-separated character strings on the command line. The value of the second parameter, exotically enough, is the name of an array of pointers to arrays. Each of those pointed-to arrays holds one of the space-separated character strings.

In the hardcopy version of this book, you learn how to include the two parameters in the main function. In preparation, suppose that the name of the first parameter is argument_count and the name of the second parameter is argument_array. Further suppose that you type the following command line:

              *-- Separating space 
              | 
              v 
analyze_trades test.data 

Then, as your program is entered, C assigns 2 to argument_count, and C assigns the address of an array of pointers to argument_array:

argument_array 
*---*---* 
|   |   |            <-- Pointer to an array of pointers 
*---*---* 
 ------- 
    |   
  *-* 
  | 
  v 
*---*---*---*---* 
|   |   |   |   |    <-- Array of pointers to character strings 
*---*---*---*---* 
 ------- ------- 
    |       | 
    |       v 
    |     *---*---*---*---*---*---*---*---*---*---* 
    |     | t | e | s | t | . | d | a | t | a | 0 | 
    |     *---*---*---*---*---*---*---*---*---*---* 
    v 
  *---*---*---*---*---*---*---*---*---*---*---*---*---*---*---* 
  | a | n | a | l | y | z | e | _ | t | r | a | d | e | s | 0 | 
  *---*---*---*---*---*---*---*---*---*---*---*---*---*---*---* 

Thus, argument_array is the name of an array of pointers to character strings; the value of argument_array is the address of the first element in a pointer array. Alternatively, the value of argument_array[0], the first element in the array, is itself the address of a character string.