In some textbooks, we can often see the form of the main function as follows: int main (int argc,char* argv[]), what are these two arguments for? How do I pass it to the main function?
1. Meaning
The first thing to know is that the main function is called by the system and passes the arguments at the same time as the call.
For example, in file file1.c, there are the following:
#include <stdio.h>int main (int argc,char* argv[]) { printf ("EXE executed!\n");}
After compiling, in the project directory of the Debug folder, you can get "File1.exe" file, we want to execute this file under DOS, we must enter the command line in a certain format, the format is as follows:
Command name parameter 1, Parameter 2, ... Parameter n
For example, to execute the above EXE file, you can enter:
File1
The following results can be obtained:
If we are passing parameters, we can enter the following:
File1 China Beijing
Now, let me tell you:
The meaning of argc is argument count: It is an int row variable that represents the number of arguments passed to the main function;
The meaning of argv is argument value: It is a pointer to a string array, each pointer element points to the specific parameters;
Can you guess what the value of argc and argv is?
Argc=3, not 2, because the command name "File1" also counts as a parameter! So from this point can also know that ARGC is constant >=1.
And what about argv? See:
2. Usage
Now that you know the meaning of each parameter, how do you use that parameter? Read the following simple procedure and you will understand:
#include <stdio.h>int main (int argc,char* argv[]) { while (argc>0) { argc--; printf ("%s\n", *argv); argv++; /* point to next parameter */ }}
To invoke the method and run the result:
Parameters of the main function