10.2. Arguments to mainFor those writing programs which will run in a hosted environment, arguments to main provide a useful opportunity to give parameters to programs. Typically, this facility is used to direct the way the program goes about its task. It's particularly common to provide file names to a program through its arguments. The declaration of main looks like this: int main(int argc, char *argv[]); This indicates that There are at least two arguments to The declaration of the char *argv[] Remember too that when it is passed to a function, the name of an array
is converted to the address of its first element. This means that we can
also declare Indeed, you will often see the declaration of int main(int argc, char **argv); When a program starts, the arguments to main will have been initialized to meet the following conditions:
To illustrate these points, here is a simple program which writes the
arguments supplied to
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
while(argc--)
printf("%s\n", *argv++);
exit(EXIT_SUCCESS);
}Example 10.1If the program name is Each time that On the system where this program was tested, a program is run by typing
its name and then the arguments, separated by spaces. This is what
happened (the $ show_args abcde text hello show_args abcde text hello $ |
The C BookThis book is published as a matter of historical interest. Please read the copyright and disclaimer information. GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested. |
|
West Yorkshire Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |