When running some other open source projects, it often appears that there are parameters after the operation. How is this achieved? How to introduce it in our own projects?
Commonly used forms:
int main(int argc, char* argv[]){
}
int main(int argc, char** argv){
}
int main(int argc, char** argv, char** envp){
}
char** argv
Represents a pointer to a character pointer, which can also be seen as an array of pointers to strings. In C/C++, command-line arguments are passed to the program as strings, so char** argv
is used to store command-line arguments.
Here is a sample program that demonstrates how to use char** argv
to get command line arguments and output them:
#include <iostream>
int main(int argc, char** argv) {
std::cout << "argc = " << argc << std::endl;
for(int i = 0; i < argc; i++) {
std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
}
return 0;
}
Run the program and pass some parameters, for example:
./example hello world 123
The output is as follows:
argc = 4
argv[0] = ./example
argv[1] = hello
argv[2] = world
argv[3] = 123
As you can see, char** argv
it points to an array of string pointers, each element points to a string, and these strings are command line parameters. The program outputs the value of each parameter in turn by traversing argv
the array.
int main(int argc, char* argv[], char* envp[])
Is the main function of the C/C++ program, it contains three parameters:
-
int argc
: Indicates the number of command line parameters, including the program itself. For example,./example arg1 arg2
when the command is executed,argc
the value of 3. -
char* argv[]
: is a pointer to character pointer to store command line arguments.argv[0]
Stores the name of the program,argv[1]
stores the first command-line argument, and so on. For example,./example arg1 arg2
when the command is executed,argv[0]
the value of is"./example"
, the value of , is .argv[1]
"arg1"
argv[2]
"arg2"
-
char* envp[]
: is a pointer to character pointer to store environment variables. Each environment variable is a string in the formatname=value
. For example,envp[0]
what is stored is"USER=john"
,envp[1]
what is stored is"HOME=/home/john"
.
Here is a simple example program that demonstrates how to use these three parameters:
#include <iostream>
int main(int argc, char* argv[], char* envp[]) {
std::cout << "argc = " << argc << std::endl;
for(int i = 0; i < argc; i++) {
std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
}
for(int i = 0; envp[i] != nullptr; i++) {
std::cout << "envp[" << i << "] = " << envp[i] << std::endl;
}
return 0;
}
The program can output the values of command-line arguments and environment variables.