tags:

views:

118

answers:

4

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()?

+1  A: 

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).

Sachin Shanbhag
+8  A: 

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
nos
EDIT: I'm wrong, you're right. I've been programming C for 12 years and never knew that. My apologies.
Graham Borland
@nos Edited my comment, and upvoted your answer. Is that new in C99?
Graham Borland
@Graham: same thing in `C89`, same section number too ( http://www.vmunix.com/~gabor/c/draft.html )
pmg
+1  A: 

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.

aJ
A: 

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.

Daniel Earwicker
envp is, perhaps, an extension of your implementation: it is not described by the Standard (`C89` or `C99`)
pmg
@pmg - fixed the answer, removing incorrect standard reference.
Daniel Earwicker
@Daniel, -1 removed
pmg