next up previous
Next: Recursion Up: intro_C Previous: structs

Passing Arguments to main()

main() is passed two arguments from the shell: an integer and a pointer to an array of strings. Traditionally these are declared as follows:

    int main(int argc,char *argv[])

Here argc (``argument count'') contains one plus the number of arguments passed to the program from the command line and argv (``argument vector'') contains a series of char pointers to these arguments. The first element in argv is always the name of the program itself, so argc is always at least 1. The library function getopt() can perform simple parsing of command-line arguments; see the listing in section 3c of the man pages. Here's a more simple example of passing two numbers and a string. Note the error trapping to force the user to conform to the expected usage:

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc,char *argv[]) {
        int m,n;
        if (argc != 4) {
            printf("Usage: %s m n filename\n",argv[0]);
            return 1;
        }
        m = atoi(argv[1]); /* convert strings to integers */
        n = atoi(argv[2]);
        printf("%s received m=%i n=%i filename=%s\n",argv[0],m,n,argv[3]);
        return 0;
    }



Massimo Ricotti 2009-01-26