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()
?
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()
?
These are for using the arguments from the command line -
argc contains the number of arguments on the command line (including the program name), and argv is the list of actual arguments (represented as character strings).
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
If you run your program like ./myprogram /tmp/somefile
These are used to pass command line paramters.
For ex: if you want to pass a file name to your process from outside then
myExe.exe "filename.txt"
the command line "filename.txt" will be stored in argv[], and the number of command line parameter ( the count) will be stored in argc.
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.