Why argv (vector argument) in C defined as pointer and what is the need to define its zeroth as program name?

advertisements
#include <stdio.h>
int main(int argc, char *argv[])
{
 int i;
 for(i=1;i<argc;i++)
  printf("%s%s", argv[i], (i<argc-1)? " ":"");
 printf("\n");
 return 0;
}

Given above is a simple C program that outputs command line inputs. Here argc is the argument counter. argv is said to be an array that contains arguments. My question is: why does it define as a pointer to a character array instead of a normal array? Also what is the need for defining its zeroth element (argv[0]) as the name by which the program is invoked.

I am a beginner and please explain it high level perspective.


The char *argv[] is a pointer that an array of char * has decayed into. For example, invoking a command like this:

$ ./command --option1 -opt2 input_file

could be viewed as:

char *argv[] = {
    "./command",
    "--option1",
    "-opt2",
    "input_file",
    NULL,
};
main(4, argv);

So basically there is an array of strings outside main, and it is passed to you in main:

    char *argv[]
    \- --/     ^
      V        |
      |   It was an array
      |
of strings


Regarding argv[0] being the invocation command, the reason is largely historical. I don't know what the first person who thought of it thought about, but I can tell at least one usefulness for it.

Imagine a program, such as vim or gawk. These programs may install symbolic links (such as vi or awk) which point to the same program. So effectively, running vim or vi (or similarly gawk or awk) could execute the exact same program. However, by inspecting argv[0], these programs can tell how they have been called and possibly adjust accordingly.

As far as I know, neither of the programs I mentioned above actually do this, but they could. For example vim called through a symbolic link named vi could turn on some compatibility. Or gawk called as awk could turn off some GNU extensions. In the modern world, if they wanted to do this, they would probably create scripts that gives the correct options, though.