Question

I am learning how to get arguments in C, however, when I run the code below with the following input, the first one becomes null.

Input: ./a.out a b c d e f g h i j k

Output: (null) b c d e f g h i j k

#include <stdio.h>

    int main(int argc, char *argv[])
    {
        int i = 2, j = 0;
        char *foo = argv[1];
        char *bar[10];
        while(j < 10 && i < argc)
        {
            bar[j++] = argv[i++];
        }
        bar[j] = NULL;

        printf("%s ", foo);
        for(j = 0; bar[j] != NULL; j++)
        {
            printf("%s ", bar[j]);
        }
        printf("\n");

        return 0;
    }
Was it helpful?

Solution

At the end of the loop you write NULL to bar[10], but you have only allocated bar[0 - 9]. That probably overwrites foo.

OTHER TIPS

You're setting bar[10] to NULL at the end of the loop, but it only goes up to bar[9]. Since foo is allocated just after bar on the stack, bar[10]=NULL overwrites foo instead.

Try

while( --argc ) puts( *++argv );

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top