Search code examples
cmallocargc

Placing an unspecified amount of command line inputs into an array in C


I essentially want to read values from the command line as typed in by the user and place them into an array. My attempt at this so far is as follows

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

#define     w   1.0


int main(int argc, char argv[])
{
    int     tmp;

    double  *x, *v, *m, *k, *R;

    x = malloc((argc-1)*sizeof(double));

    printf("%lf\n", argc);

    for(tmp=0; tmp<argc-1; tmp++)
    {
        x[tmp] = argv[tmp+1];
        printf("%lf\n", x[tmp]);
    }
}

The print of the value of argc is equal to 0 yet the for loop will repeat three times which doesn't make sense and the values it gives are just completely wrong. Sorry i'm a bit of an amateur at this. Thanks in advance!


Solution

  • There are many problems with your code, some already mentioned by others such as argv that needs to have a type of char *[].

    First of all, if argc is 1, then your malloc will fail because allocating memory of size 0 doesn't make sense.

    Second, printf("%lf\n", argc); is incorrect. argc is int and you need to use %d to print it. The reason you see 0, which is wrong, is this.

    Third, x[tmp] = argv[tmp+1]; is incorrect too. argv[tmp+1] is a char *, which means it's a string. While x[tmp] is a double. You can't just assign a string to a double. What you need to do is to convert the string to a double, for example:

    sscanf(argv[tmp+1], "%lf", &x[tmp]);
    

    or

    x[tmp] = strtod(argv[tmp+1]);
    

    Hint: always compile your code with common warnings. With gcc, that would be -Wall command line argument. The compiler can tell you about many of these mistakes.