How to convert array of char into array of int in C Programming?

Viewed 615
#include<stdio.h>

#include<stdlib.h>

#define LENGTH 5 

void convert ( char parray[] ,int array[] )

{

    int i; 
    for (i=0; i< LENGTH; i++)
    {
        array[i] = atoi(&parray[i]);
        printf(" The converted array is %d\n" , array[i]);
    }
}

int main ()

{

    char parray[LENGTH] = { '7', '1', '4','5' ,'2'};

    int iarray[LENGTH];

    convert(parray, iarray);
}

******** Output *********

The converted array is 71452

The converted array is 1452

The converted array is 452

The converted array is 52

The converted array is 2

But I want the following output like this

The converted array is 7

The converted array is 1

The converted array is 4

The converted array is 5

The converted array is 2

It should store value of 7 in array[0] , 1 in array[1] !!!! Please help

3 Answers

atoi() is for converting strings (sequences of characters terminated by a null-character) to integers. To convert single character to an integer, you can subtract '0' (the character code of 0) from the character because it is guaranteed in C specification that character codes for decimal digits are continuous.

void convert ( char parray[] ,int array[] )

{

    int i; 
    for (i=0; i< LENGTH; i++)
    {
        array[i] = parray[i] - '0';
        printf(" The converted array is %d\n" , array[i]);
    }
}

This statement

array[i] = atoi(&parray[i]);

invokes undefined behavior because the character array parray does not contain a string: a sequence of characters terminated with the zero character '\0'. And the function atoi expects a string as its argument.

Instead you could write

array[i] = parray[i] - '0';

Character '0' through up to '9' have an increased by 1 sequence of codes. So for example if to write '3' - '0' you will get the integer number 3.

You are confusing single characters with character strings. The latter are sequences of characters (arrays) terminated with a nul (zero value) character, and that is what the atoi function expects as its input.

To convert a single character digit to its numerical value, you just need to subtract the value of the zero digit ('0') from that character's value (the values of the numerical digits are guaranteed by the Standard to be contiguous).

So, rather than:

array[i] = atoi(&parray[i]);

use:

array[i] = parray[i] - '0'; // Will work if (and only if) parray[i] is a digit.

What is happening in your code is that (by chance) there is a zero byte immediately after the end of your 5-character array (but you can not rely on this), so each atoi(&parray[i]) call is passing a character string starting with, respectively, the '7', '1', '5', '4' and '2' characters, and ending only after the '2'. Thus, you are getting values that represent the numbers formed by the concatenation of your individual array digits. But I repeat: you cannot rely on there being a zero-value character after your array!

Related