tags:

views:

71

answers:

2

I want to use my program like this:

./program -I /usr/include/ /usr/bin/ /usr/local/include/ ...

Where the switch can go on and on like in a var args list. How could I do that in C99? Preferably get a something like char **args_list or char *args_list[] that contains all of the things like /usr/include and /usr/bin/.

+7  A: 

The output of running the following code:

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; ++i)
    {
        printf("%s\n", argv[i]);
    }
}

Executed by program -I /usr/include/ /usr/bin/ /usr/local/include/

Output:

-I
/usr/include/
/usr/bin/
/usr/local/include/

Note that in the code example the initial index is 1. This is because the first pointer in the argv variable is the name of the program. In this case it would be program.

linuxuser27
Thanks for the answer, I just have one more quick question. Check the update!
Mohit Deshpande
A: 

Your program in the update is probably segfaulting because you're running off the end of the array:

    printf("%s\n", argv[2]);

there's no guarantee there is an argv[2].

(It may be null if argc==2, but I think not all printfs cope with that.)

poolie