Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the arguments to main() for?

Tags:

c

arguments

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

like image 264
Deven Avatar asked Sep 17 '10 09:09

Deven


People also ask

What is the purpose of arguments in main method?

Like any function arguments, the purpose is not to make calling code work, but to provide data that the called function needs in order to operate correctly. In the case of a main function, this is how the calling environment tells your program what options were given on the command line.

How many arguments can be passed to main () is?

Explanation: None. 3. How many arguments can be passed to main()? Explanation: None.

Can we pass arguments in main ()?

Yes, we can give arguments in the main() function. Command line arguments in C are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution. The argc and argv are the two arguments that can pass to main function.

Why we are using main () in C in?

A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. A main() function is used to invoke the programming code at the run time, not at the compile time of a program.


2 Answers

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
like image 97
nos Avatar answered Oct 13 '22 05:10

nos


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.

like image 33
Daniel Earwicker Avatar answered Oct 13 '22 03:10

Daniel Earwicker