|
10. Command-line Arguments
|
|
When main is called, it is called with two arguments. |
– argc (for argument count): the number of command-line arguments the program was invoked with
– argv (for argument vector): a pointer to an array of character strings that contain the arguments, one per string. |
The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks. That is, the command
|
echo hello, world |
|
|
|
– a is a true two-dimensional array: 200 int-sized locations have been set aside, and the conventional rectangular subscript calculation 20 * row +col is used to find the element a[row,col].
– b is the definition only allocates 10 pointers and does not initialize them. The important advantage of the pointer array is that the rows of the array may be of different lengths. |
|
Example |
|
char *name[] = { "Illegal month", "Jan", "Feb", "Mar" }; |
|
|
|
|
Example |
#include <stdio.h>
/* echo command-line arguments; 1st version */
int main(int argc, char *argv[])
{
int i;
for (i=1; i<argc; i++)
printf(“%s%s”, argv[i], (i<argc-1) ? “ ” : “”);
printf(“\n”);
return 0;
}
/* echo command-line arguments; 2nd vesion */
int main(int argc, char *argv[])
{
while (--argc > 0)
printf(“%s%s”, *++argv, (argc>1) ? “ ” : “”);
printf(“\n”);
return 0;
}
|
|
|
|
|
|
|
|