使用atoi将char数组转换为整数导致分段错误

时间:2014-10-21 14:41:21

标签: c arrays segmentation-fault

我正在尝试使用atoi将char数组转换为整数。但是下面的代码会产生分段错误。

CODE:

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

int main(){
    char a[10] = "1234567890";
    int x,i;
    for(i=0;i<strlen(a);i++){
        x=atoi(a[i]);
        printf("%d",x);
    }
    return 0;
}

我做错了什么,是否可以使用而不是使用atoi

1 个答案:

答案 0 :(得分:3)

char a[10] = "1234567890";

这为null终止符留下了空间。因此strlen(a)会导致未定义的行为。像这样声明a

const char a[] = "1234567890";

或者像这样:

const char *a = "1234567890";

随后,您对atoi的呼叫不正确。您应该将指针传递给以null结尾的字符串。您传递char。也许你的意思是通过a+i

x=atoi(a+i);

然后,为什么你要循环并不是很明显。出了什么问题:

x = atoi(a);

此外,atoi是一个众所周知的功能。它没有为您提供任何有意义的方法来检测输入中的错误。更好的方法是使用sscanf

你可以像这样把所有这些放在一起:

#include<stdio.h>

int main(void)
{
    const char *a = "1234567890";
    for(size_t i = 0; a[i]; i++)
    {
        int x;
        if (sscanf(a + i, "%d", &x) == 1)
        {
            printf("%d\n", x);
        }
    }

    return 0;
}

输出是:

1234567890
234567890
34567890
4567890
567890
67890
7890
890
90
0

但我怀疑这是你想要的。我怀疑你真的想要这个:

#include<stdio.h>

int main(void)
{
    int x;
    if (sscanf("1234567890", "%d", &x) == 1)
    {
        printf("%d\n", x);
    }
    return 0;
}

输出结果为:

1234567890
相关问题