user8715337
user8715337

Reputation:

Segmentation fault (core dumped) - C

This is part of program, where I need to know if arguments are int. I can't understand why I have this error 'Segmentation fault (core dumped)'.

int main(int argc,char* argv[])
{
    int i = 1;
    while(i < argc)
    {
        if(isdigit(argv[i]))
            printf("OK\n");
        else
            printf("NOT OK\n"); 
        i++;
    }
}

Upvotes: 0

Views: 6673

Answers (4)

boriaz50
boriaz50

Reputation: 856

argv[i] has char* type, but isdigit() expects int (ASCII code of char is being casted to int automatically).

Write separate function to check if string contains digits only.

#include <ctype.h>
#include <stdbool.h>

bool is_string_number(const char* str)
{
    while (*str)
    {
        if (!isdigit(*str++))
            return false;
    }
    return true;
}

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; ++i)
        printf(is_string_number(argv[i]) ? "OK\n" : "NOT OK\n");

    return 0;
}

Upvotes: 0

Nicolas Guerin
Nicolas Guerin

Reputation: 366

This is what you're looking for.

 int main(int argc,char* argv[])
    {
        int i = 1;
        int j;
        while(i < argc)
        {
            j = 0;
            while (argv[i][j] != 0)
            {
                if(isdigit(argv[i][j]))
                    printf("OK\n");
                else
                    printf("NOT OK\n"); 
                j++;  
            }
            i++;
        }
    }

argv[i] is pointer, not a data. You're passing a pointer where a char (i think) is expected.

You should compile your file using the warnings flags with gcc : -w -Wall -Wextra it will tell you that you're passing the wrong type of argument.

If is digit takes an int you've have to convert the argv[i][j] into an int with atoi(argv[i][j])

Upvotes: 1

YaatSuka
YaatSuka

Reputation: 231

isdigit() takes an int as argument, but here you pass a char *.
So, you have to make a loop on each string:

int main(int argc,char* argv[])
{
    int i = 1;
    int j;
    while(i < argc)
    {
        j = -1;
        while (argv[i][++j] != 0)
        {
            if(isdigit(argv[i][j]))
                printf("OK\n");
            else
                printf("NOT OK\n"); 
        }
        i++;
    }
}

Upvotes: 1

Jens
Jens

Reputation: 72786

argv[i] is a ptr-to-char, but isdigit() takes an int. No wonder the program crashes. Did you mean to use isdigit(argv[x][y]) somehow?

Upvotes: 0

Related Questions