Possible Duplicate:
argc and argv in main
I’m having difficulty understanding the notation used for the general main function declaration, i.e. int main(int argc, char *argv[]). I understand that what is actually passed to the main function is a pointer to a pointer to char, but I find the notation difficult. For instance:
Why does **argv point to the first char and not the whole string? Likewise, why does *argv[0] point to the same thing as the previous example.
Why does *argv point to the whole first string, instead of the first char like the previous example?
This is a little unrelated, but why does *argv + 1 point a string ‘minus the first char’ instead of pointing to the next string in the array?
Consider a program with
argc == 3.The variable
argvpoints to the start of an array of pointers.argv[0]is the first pointer. It points at the program name (or, if the system cannot determine the program name, then the string forargv[0]will be an empty string;argv[0][0] == '\0').argv[1]points to the first argument,argv[2]points to the second argument, andargv[3] == 0(equivalentlyargv[argc] == 0).The other detail you need to know, of course, is that
array[i] == *(array + i)for any array.You ask specifically:
*argvis equivalent to*(argv + 0)and henceargv[0]. It is achar *. When you dereference achar *, you get the ‘first’ character in the string. And**argvis therefore equivalent to*(argv[0])or*(argv[0] + 0)orargv[0][0].(It can be legitimately argued that
**argvis a character, not a pointer, so it doesn’t ‘point to the first char’. It is simply another name for the'p'of"program name\0".)As noted before,
argv[0]is a pointer to the string; therefore*argv[0]must be the first character in the string.This is a question of convention.
*argvpoints at the first character of the first string. If you interpret it as a pointer to a string, it points to ‘the whole string’, in the same way thatchar *pqr = "Hello world\n";points at ‘the whole string’. If you interpret it as a pointer to a single character, it points to the first character of the string. Think of it as like wave-particle duality, only here it is character-string duality.*argv + 1is(*argv) + 1. As already discussed,*argvpoints at the first character of the first string. If you add 1 to a pointer, it points at the next item; since*argvpoints at a character,*argv+1points to the next character.*(argv + 1)points to the (first character of the) next string.