Command Line Argument: 'Main' Prototype
Command Line Argument: 'Main' Prototype
Command Line Argument: 'Main' Prototype
Command line arguments are arguments for the main function. main is basically a function
It can receive arguments like other functions. The ‘calling function’ in this case is the operating
system, or another program
'main' prototype
int main(int argc, char* argv[])
When we want main to accept command line arguments, we must define it like this
• argc holds the number of arguments that were entered by the caller
• argv is an array of pointers to char – an array of strings – holding the text values of the
arguments. The first argument is always the program’s name
$ gedit cmdProgram.c
$ gcc -o cmdProgram cmdProgram.c
$ ./cmdProgram I love C program
======output=========
So the first argument argv[ ], that is argv[0] is always the program name, the other
arguments followed from argv[1], argv[2], etc, argc giving the total number of arguments
In windows you can specify these arguments directly, by using the Windows console (Start
Run…, then type ‘cmd’ and drag the executable into the window. Then type the arguments
and <Enter>)
Example
Write a program that accepts two numbers as command line arguments, representing a
rectangle’s height and width (as floating-point numbers). The program should display the
rectangle’s area and perimeter
Solution
int main(int argc, char* argv[])
{
double width, height;
if (argc != 3) {
printf("Wrong number of arguments!\n");
return 1;
}
width = atof(argv[1]);
height = atof(argv[2]);