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

前端 未结 8 2127
萌比男神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:46

    int main();
    

    This is a simple declaration. It cannot take any command line arguments.

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

    This declaration is used when your program must take command-line arguments. When run like such:

    myprogram arg1 arg2 arg3
    

    argc, or Argument Count, will be set to 4 (four arguments), and argv, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram) is included in the arguments!

    Alternatively, you could use:

    int main(int argc, char** argv);
    

    This is also valid.

    There is another parameter you can add:

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

    The envp parameter also contains environment variables. Each entry follows this format:

    VARIABLENAME=VariableValue
    

    like this:

    SHELL=/bin/bash    
    

    The environment variables list is null-terminated.

    IMPORTANT: DO NOT use any argv or envp values directly in calls to system()! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system(). There is almost always a better solution implemented through C libraries.

提交回复
热议问题