What are the arguments to main() for?

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

Leave a Comment