Search code examples
cpointersatoi

How to use atoi() to convert an element of a char array to int?


Here is the code:

char *P_char = malloc(sizeof(char)*10);

int i = 0;

for(i; i < 10; i++)
{
    P_char[i] = (char)(i + 48);
}

and here are some of the code that I have tried in order to use atoi

printf("The int result is: %d", atoi(P_char[4]));

and

int converted = atoi(P_char[4]);
printf("The int result is: %d", converted );

and

const char x = P_char[4];
int converted = atoi(x);
printf("The int result is: %d", converted );

But still doesn't work. I couldn't find out if atoi() is not supposet to be used for pointers. Is there such a fact?

NOTE: When I say doesn't work I mean program exits with error code instead of executing till the end.


Solution

  • If you have such statement

    const char x = P_char[4];
    

    then to output the digit stored in x as an integer you can the following way

    printf("The int result is: %d", x - '0' );
    

    As for the function atoi then it is applied to strings not to a single character.