int main(int argc, char *argv[])的用法
本文最后更新于 3198 天前,其中的信息可能已经有所发展或是发生改变。

解释源自此处: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)等价。

评论

  1. 9 年前
    2016-4-04 16:56:45
    Google Chrome 48.0.2564.97 Google Chrome 48.0.2564.97 Windows 8.1 x64 Edition Windows 8.1 x64 Edition

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

    • 博主
      fawdlstty
      9 年前
      2016-4-04 17:11:58
      Google Chrome 49.0.2623.108 Google Chrome 49.0.2623.108 Windows 7 x64 Edition Windows 7 x64 Edition

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

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇