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

前端 未结 8 2121
萌比男神i
萌比男神i 2020-11-21 05:18

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

8条回答
  •  走了就别回头了
    2020-11-21 05:40

    Suppose you run your program thus (using sh syntax):

    myprog arg1 arg2 'arg 3'
    

    If you declared your main as int main(int argc, char *argv[]), then (in most environments), your main() will be called as if like:

    p = { "myprog", "arg1", "arg2", "arg 3", NULL };
    exit(main(4, p));
    

    However, if you declared your main as int main(), it will be called something like

    exit(main());
    

    and you don't get the arguments passed.

    Two additional things to note:

    1. These are the only two standard-mandated signatures for main. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.
    2. *argv[] and **argv are exactly equivalent, so you can write int main(int argc, char *argv[]) as int main(int argc, char **argv).

提交回复
热议问题