int main(int argc, char *argv[])的用法

解释源自此处:http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean

原问题:

In many C++ IDE's and compilers, when it generates the main function for you, it looks like this:

int main(int argc, char *argv[])

When I code C++ without an IDE, just with a command line compiler, I type:

int main()

without any parameters. What does this mean, and is it vital to my program?

翻译:

在许多c++IDE和编译器里,main函数经常会像这样:

int main(int argc, char *argv[])

但是我写的时候只会这样:

int main()

米有任何包含。这样做的目的是什么?

解释:

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

c3

意思就是,int main(int argc, char *argv[])是命令行里用的

argc表示后面接的参数个数

比如:

#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;
    }
}

运行命令:

./test a1 b2 c3

输出:

./test
a1
b2
c3

另外,int main(int argc, char *argv[])与int main(int argc, char **argv)等价。

“int main(int argc, char *argv[])的用法”的2个回复

  1. Google Chrome 48.0.2564.97 Google Chrome 48.0.2564.97 Windows 8.1 x64 Edition Windows 8.1 x64 Edition
    Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36

    写掉了一个参数 标准写法应该是这样int main(int argc, char* argv[], char* envp[])

    1. Google Chrome 49.0.2623.108 Google Chrome 49.0.2623.108 Windows 7 x64 Edition Windows 7 x64 Edition
      Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36

      环境变量啊。。。。感觉用到的地方好少,,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*(必填)