It is possible to pass arguments to C programs when they are
executed. The brackets which follow main are used for this purpose. argc
refers to the number of arguments passed, and argv[] is a pointer array
which points to each argument which is passed to
mainA simple example follows, which checks to see if a single argument is supplied on the command line when the program is invoked.
#include <stdio.>h
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 name of the program invoked, which means
that *argv[1] is a pointer to the first 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. The program is called
by the command line:
More clearly, Suppose a program is compiled to an executable program
myecho and that the program is executed with the following command.
When this command is executed, the command interpreter calls the
main() function of the myprog program with 4 passed as the argc argument
and an array of 4 strings as the argv argument.
argv[0] - "myprog"
argv[1] - "aaa"
argv[2] - "bbb"
argv[3] - "ccc"
|
www.cinterviews.com appreciates your contribution please mail us the questions you have to
cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community
No comments:
Post a Comment