I'm trying to check that the third command line is a digit so I did

int n;
if (!isdigit(argv[3]))
        fprintf(stderr, "n MUST be a number");
        return 4;
    } else 
        n = atoi(argv[3]);

but I'm getting

Segmentation fault

how ever if I try this

int n = atoi(argv[3]);

it works just fine, I don't really understand why


isdigit takes a single char as input; if you pass it a string, it will segfault. If you really want to check if argv[3] is numeric, you will have to iterate over each character and check it individually. You probably did something like that in the Vigenere problem, when testing whether the key was alphabetic?


I actually found the solution and it was very easy,

I should put if(!isdigit(*argv[3])

to explain this, let's look at char *argv[] in the main function parameters, it's really an array of strings, so when we say if (!isdigit(argv[3])) that means we are passing the third string in argv, but what a string actually is? it is an array of char, so it's actually the same as a 2d array, and so we could've said if(!isdigit(argv[3][1])) or we can use star as we did in here as it means a pointer to the first element in the array which is the same as saying if(!isdigit(argv[3][1]))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .