Search code examples
catoi

How do I fix output from command-line arguments to printing out the correct integers?


#define N 10

int main(int argc, char *argv[])
{
    int *a = malloc(sizeof(N));
    int i;

    for(i = 1; i < argc; i++) {
        *(a++) = atoi(argv[i]);
    }

    i = 0;
    while(i < N) {
        printf("%d ", *(a++));
        i++;
    }
}

I'm confused on why my output is all 0s. I'm not really sure how to fix it since i am new to command-line arguments / pointers. A background for this program is that it takes in integers, then is supposed to convert them from strings to integers using atoi then print the new array back out using pointer arithmetic.


Solution

  • There's a lot wrong with this.

    sizeof(N) gives the size of an integer constant (probably 4 bytes). What you mean is malloc(N * sizeof(int)); But there's not much point using malloc if N is mall and you know it at compile time. You want to malloc argc ints. Then the program will scale to millions of commandline arguments, assuming the shell allows such a long line to be entered.

    Then when you malloc a pointer, you need to hang onto it. Don't increment it. If you want a travelling pointer, use two pointers, a and ptr. a points to the buffer and "owns" it, ptr is a temporary that moves along. However array syntax a[i] is almost always preferable to travelling pointers.

    Then the final while will print garbage values if argc is less than N. that might be want you want in a learning exercise / exploratory programming, but not what you normally hope to achieve.