固定分段故障:11 [英] Fixing a Segmentation fault: 11

查看:195
本文介绍了固定分段故障:11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试转换为整数的字符串(如509为char类型)为int在C.然而,一旦我添加了检查,看看是否值应为负值I code的部分得到一个分割错误。我试着做一些研究,发现其因为使用指针错误或访问内存的我没有权限。但我似乎无法弄清楚我要去哪里错了。这是我的第一个C类,所以我是新来的,任何帮助将非常AP preciated。
谢谢!

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.\n"); 
            }
            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.!\n"); 
            }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\n",asInteger);
    }
else {
    printf("incorrect function number"); 
}
return 0; 
}

在code工作时,该功能仅此

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.!\n"); 
        }else{
        value = value * 10 + (string[i] - '0');
        }
    }
    return value;   
}

但一旦我添加了其他的循环来检查它开始给我的分段错误负号:11

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

推荐答案

马特·麦克纳布已经暗示

Matt McNabb already hinted

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

是错误的。 STRCMP希望两个字符串,你给它一个char和一个字符串。做

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

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

是的,从来没有忽略警告,编译器正试图帮助你。虽然这是值得商榷的,它没有帮助,如果它不是fatalled你会试图修复它。

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

这篇关于固定分段故障:11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆