What is Command-Line Arguments?

In every program you have seen so far, the main function has had no dummy arguments between its parentheses. The main function is allowed to have dummy arguments and they match up with command-line arguments used when the program is run.

The two dummy arguments to the main function are called argc and argv:

  • argc contains the number of command-line arguments passed to the main program and
  • argv[] is an array of pointers-to-char, each element of which points to a passed command-line argument.

Example

A simple example follows, which checks to see if only a single argument is supplied on the command line when the program is invoked

#include <stdio.h>
 
int main(int argc, char* argv[]) 
{ 
	if (argc == 2) {
		printf("The argument supplied is %s\n", argv[1]);
	} 
	else if (argc > 2) { 
		printf("Too many arguments supplied.\n"); 
	}
	else {
		printf("One argument expected.\n"); 
	}
}

Note that *argv[0] is the program name itself, which means that *argv[1] is a pointer to the first “actual” argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one. Thus for n arguments, argc will be equal to n+1.