简体   繁体   中英

C Segmentation fault using Argv[]

I am new to C programming and I am getting a Segmentation Fault when passing a single character and trying to vailidate if it is a digit.

Here is a sample:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if (isdigit(argv[argc-1]))
    {
        printf("Use only one Argument%i\n", argc);
        return 1;
    }

    return 0;
}

As Eugene said, argv[argc-1] is of type char* as it was meant to hold a string. The segmentation fault is probably a result of lookup.

Assuming you would like to test the first character of the last argument, this should be written like this:

if (isdigit(argv[argc-1][0]))
{
    printf("Use only one Argument%i\n", argc);
    return 1;
}

You can also use the '*' notation to defer to the first char, but I believe [0] will be slightly more readable in this case.

Yeah, I am also posting an answer that checks if all the inputs are digits. So it does not just look at the first input from the command line. This way you can put any amount of digits.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char *argv[]) {
        //need to figure out how many "words" user wrote
        for(int i = 1; i<= argc-1; i++) {
                int stringLength = strlen(argv [i]);
                for( int j =0; j < stringLength; j++) {
                        if (!isdigit(argv[i][j]) ){
                                printf("Use only digits\n");
                                return 1;
                        }
                }

        }
        return 0;

}
Example one : 

./stackQuestion 1
Example two: 

./stackQuestion 1o1
Use only digits
Example three:

./stackQuestion 1 1 101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM