Stuxnet78 Stuxnet78 - 19 days ago 6
C Question

Conversion of char array to integer using atoi caused segmentation fault

I'm trying to convert a char array to an integer using

atoi
. 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
?

Answer
char a[10] = "1234567890";

This leaves no room for the null terminator. And so strlen(a) results in undefined behaviour. Declare a like this:

const char a[] = "1234567890";

or like this:

const char *a = "1234567890";

Subsequently, your call to atoi is incorrect. You are meant to pass a pointer to a null terminated string. You pass a char. Perhaps you mean to pass 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. It doesn't give you any meaningful way to detect errors in your input. A better approach would be to use 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