Command Line Arguments and Strings ---------------------------------- Reference: Sections 12.4 and 9.1 in C book Arguments can be passed to any function, including the main() function. "main()", has a set format for its arguments This format is: main(int argc, char **argv) or you may also see it written as main(int argc, char *argv[]) Both are equivalent. To use these arguments, you simple need to refer to them in your program using either conversions to integers or floating point numbers or use them as strings. "argv" contains all the arguments (args) or strings in ascii. Example: program apple banana 10 9.8 argv[0] The name of the program. argv[1] The first argument "apple" argv[2] The 2nd argument "banana" argv[3] The 3rd argument "10" argv[4] The 4th argument "9.8" You could have more or fewer arguments. It is up to you. The variable "argc" contains the number of arguments entered on the command line plus the name of the program. In this case there are 4 args + 1 for the name of the program. Therefore, argc = 5 . You can use "argc" in your program to see how many args are there and if the number is not what was expected, have the program give an error message and then exit. An example might be: #include #include main(int argc, char *argv[]) { int a,b; if(argc != 3) /* are there not 3 args including the program name */ { printf("usage: program value1 value2\n\n"); printf("value1 : The rate...\n"); printf("value2 : The time...\n"); exit(0); /* this exits the C program */ } a = atoi(argv[1]); b = atoi(argv[2]); printf("a = %d, b = %d\n",a,b); } Examples are: %program 10 usage: program value1 value2 value1 : The rate... value2 : The time... %program 10 2 a = 10, b = 2 %program 10 10 10 usage: program value1 value2 value1 : The rate... value2 : The time... If you wanted, you could leave the args in their ascii string format. These may be viewed using the "%s" printf() specification. This is done as: printf("The first argument is: %s\n",argv[1]); If the first argument was "orange" then the output would be: The first argument is: orange If the first argument was "9.88" then the output would be: The first argument is: 9.88 The variable "argv" is an array of strings. "argv[1]" refers to the first string, "argv[2]" the second, etc... Strings, once again, are lists of characters. That is why "argv" is declared as a char ** type variable. char a declaration of a character char a[5] declaration of 5 characters (this may be written as char *a and then using memory allocation routines declared to be 5 characters (an advanced topic). char a[2][5] declaration of 2 lists of 5 characters, or 2 strings of length 5. Again, this may be written as char **a or char *a[5], but this is a more advanced topic (so ignore for now).