In "Accelerated C++: Practical Programming by Example", it says
Now that we understand pointers and character arrays, we can understand how to pass arguments to the main function. Most operating systems provide a way to pass a sequence of character strings to main as an argument, if the main function is willing to accept them. The way the author of main signals such willingness is by giving main two parameters: an int and a pointer to a pointer to char. Like any parameters, these can have arbitrary names, but programmers often call them argc and argv. The value of argv is a pointer to the initial element of an array of pointers, one for each argument. The value of argc is the number of pointers in the array of which argv points to the initial element. The initial element of that array always represents the name by which the program is called, so argc is always at least 1. The arguments, if any, occupy subsequent elements of the array.
As an example, this program writes its arguments, if any, with spaces between them:
int main(int argc, char** argv) {
// if there are arguments, write them if (argc > 1) {
int i;
// declare i outside the for because we need it after the loop finishes
for (i = 1; i < argc-1; ++i)
cout << argv[i] << " ";
cout << argv[i] << endl;
return 0;
}
// write all but the last entry and a space // argv[i] is a char*
// write the last entry but not a space
what I don't understand is this sentence "The value of argc is the number of pointers in the array of which argv points to the initial element. The initial element of that array always represents the name by which the program is called, so argc is always at least 1. "
what is argv[0]?
argv
andargc
being0
. It is also possible to put whatever string you want intoargv[0]
- it is purely a convention that it be the name of the program, you cannot rely on that. – Jesper Juhlargc
isn't 0 you get either the invocation of the program or an empty string. Note invocation of the program doesn't necessarily mean the name of the program. Symlinks, for example can break your expectations very quickly. – user4581301argc
is the number of pointers in the array of whichargv
points to the initial element.", as the arrayargv
is null-pointer-terminated, meaning it contains at leastargc + 1
pointers (of which the firstargc
point to valid strings). – gha.stargv
, so I can makeargv[0]
be "hello world" or any other arbitrary string. – Jesper Juhl