Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm currently trying to convert an integer string (like "509" as type char) to an int in C. However once I added the portion of code that checked to see if the value should be negative I get a segmentation error. I tried doing some research and found that its because of using pointers wrong or accessing memory I don't have permission to. But I can't seem to figure out where I'm going wrong. This is my first C class so I am new to it, any help would be much appreciated. Thanks!

#include <stdio.h>
#include <string.h>

int toInteger(char *string){
    int length = strlen(string); 
    int value = 0; 
    if(strcmp(string[0], "-") == 0){
        for(int i = 1; i < length; i ++){
            if((string[i] - '0') < 0 || (string[i] - '0') > 9){
                printf("string must be entirely numeric values.
"); 
            }
            else{
                value = value * 10 + (string[i] - '0');
            }
        }
        value = value * -1; 
    }
    else{

        for(int i = 0; i < length; i ++){
            if((string[i] - '0') < 0 || (string[i] - '0') > 9){
                printf("string must be entirely numeric values.!
"); 
            }else{
            value = value * 10 + (string[i] - '0');
            }
        }
    }
    return value;   
}

int main(int argc, char *argv[]){

int x = argc; 
char *variable = argv[1]; 
char *function = argv[2];

if(strcmp(function,"1") == 0){
        int asInteger = toInteger(variable);
        printf("%d
",asInteger);
    }
else {
    printf("incorrect function number"); 
}
return 0; 
}

The code worked when the function was only this

int toInteger(char *string){
int length = strlen(string); 
int value = 0; 

    for(int i = 0; i < length; i ++){
        if((string[i] - '0') < 0 || (string[i] - '0') > 9){
            printf("string must be entirely numeric values.!
"); 
        }else{
        value = value * 10 + (string[i] - '0');
        }
    }
    return value;   
}

but once I added the other loop to check for a negative sign it started giving me the segmentation fault: 11

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

Matt McNabb already hinted

if(strcmp(string[0], "-") == 0){

is wrong. strcmp wants two strings, you gave it a char and a string. Do

if(string[0] == '-')){

And yes, never ignore warnings, the compiler is trying to help you. Although it is arguable that its not helping, if it had fatalled instead you would have tried to fix it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...