What does int main(int argc, char *argv[]) mean?

忽然发现自己不理解许多代码中这行的含义是什么。。。(汗颜)

下面贴一段stackoverflow上面的回答:

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

Try the following program:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

Running it with ./test a1 b2 c3 will output:

Have 4 arguments:
./test
a1
b2
c

int main(int argc, char *argv[])是Linux和Unix中的标准写法,在命令行中传参数这样可以接收参数,argc表示后面的参数个数+1(这里的加1代表程序运行的全路径名或程序的名字,如上面代码输出的./test),argv为参数的字符串数组的指针。int main()则当不传入参数时使用。

 

但是还有一种写法:int main(int argc, char* argv[], char* envp[]),后面的char* envp[]是用来取得系统的环境变量

如图为test.cpp代码:

 

 

 编译,链接后执行可得

 

posted @ 2022-11-13 11:07  DUTliu  阅读(291)  评论(0编辑  收藏  举报