What is the type of command-line argument `argv` in C?

Jin picture Jin · Aug 23, 2016 · Viewed 11.5k times · Source

I'm reading a section from C Primer Plus about command-line argument argv and I'm having difficulty understanding this sentence.

It says that,

The program stores the command line strings in memory and stores the address of each string in an array of pointers. The address of this array is stored in the second argument. By convention, this pointer to pointers is called argv, for argument values .

Does this mean that the command line strings are stored in memory as an array of pointers to array of char?

Answer

haccks picture haccks · Aug 23, 2016

argv is of type char **. It is not an array. It is a pointer to pointer to char. Command line arguments are stored in the memory and the address of each of the memory location is stored in an array. This array is an array of pointers to char. argv points to first element of this array.

                  Some
                  array

                 +-------+        +------+------+-------------+------+
argv ----------> |       |        |      |      |             |      |
                 | 0x100 +------> |      |      | . . . . . . |      |  Program Name1
         0x900   |       |        |      |      |             |      |
                 |       |        +------+------+-------------+------+
                 +-------+         0x100  0x101
                 |       |        +------+------+-------------+------+
                 | 0x205 |        |      |      |             |      |
         0x904   |       +------> |      |      | . . . . . . |      |  Arg1
                 |       |  .     |      |      |             |      |
                 +-------+        +------+------+-------------+------+
                 |  .    |  .      0x205  0x206
                 |  .    |
                 |  .    |  .
                 |  .    |
                 +-------+  .     +------+------+-------------+------+
                 |       |        |      |      |             |      |
                 | 0x501 +------> |      |      | . . . . . . |      |  Argargc-1
                 |       |        |      |      |             |      |
                 +-------+        +------+------+-------------+------+
                 |       |         0x501  0x502
                 | NULL  |
                 |       |
                 +-------+


0xXXX Represents memory address


1. In most of the cases argv[0] represents the program name but if program name is not available from the host environment then argv[0][0] represents null character.