What are the arguments to main() for?

Everytime I create a project (standard command line utility) with Xcode, my main function starts out looking like this:

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

What's all this in the parenthesis? Why use this rather than just int main()?


Solution 1:

main receives the number of arguments and the arguments passed to it when you start the program, so you can access it.

argc contains the number of arguments, argv contains pointers to the arguments. argv[argc] is always a NULL pointer. The arguments usually include the program name itself.

Typically if you run your program like ./myprogram

  • argc is 1;
  • argv[0] is the string "./myprogram"
  • argv[1] is a NULL pointer

If you run your program like ./myprogram /tmp/somefile

  • argc is 2;
  • argv[0] is the string "./myprogram"
  • argv[1] is the string "/tmp/somefile"
  • argv[2] is a NULL pointer

Solution 2:

Although not covered by standards, on Windows and most flavours of Unix and Linux, main can have up to three arguments:

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

The last one is similar to argv (which is an array of strings, as described in other answers, specifying arguments to the program passed on the command line.)

But it contains the environment variables, e.g. PATH or anything else you set in your OS shell. It is null terminated so there is no need to provide a count argument.