简体   繁体   English

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

[英]Conversion of char array to integer using atoi caused segmentation fault

I'm trying to convert a char array to an integer using atoi . 我正在尝试使用atoi将char数组转换为整数。 But the code below produces a segmentation fault. 但是下面的代码会产生分段错误。

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;
}

What have I done wrong and is ther anything I can use instead of using atoi ? 我做错了什么,还有什么可以代替atoi使用的?

char a[10] = "1234567890";

This leaves no room for the null terminator. 这为空终止符留出了空间。 And so strlen(a) results in undefined behaviour. 因此strlen(a)导致不确定的行为。 Declare a like this: 声明a这样的:

const char a[] = "1234567890";

or like this: 或像这样:

const char *a = "1234567890";

Subsequently, your call to atoi is incorrect. 随后,您对atoi的呼叫不正确。 You are meant to pass a pointer to a null terminated string. 您应该将指针传递给以空终止的字符串。 You pass a char . 您传递了一个char Perhaps you mean to pass a+i : 也许您的意思是通过a+i

x=atoi(a+i);

Then again, it's not at all obvious why you are looping. 再说一遍,循环的原因一点也不明显。 What's wrong with: 有什么问题:

x = atoi(a);

Also, atoi is a notoriously gnarly function to use. 同样, atoi是个臭名昭著的功能。 It doesn't give you any meaningful way to detect errors in your input. 它没有提供任何有意义的方式来检测输入中的错误。 A better approach would be to use sscanf . 更好的方法是使用sscanf

You might put this all together like so: 您可以像这样将所有内容放在一起:

#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;
}

The output of that is: 输出为:

1234567890
234567890
34567890
4567890
567890
67890
7890
890
90
0

But I doubt that's what you want. 但是我怀疑那是你想要的。 I suspect that you really want this: 我怀疑您真的想要这样:

#include<stdio.h>

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

The output is: 输出为:

1234567890

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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