converting contents of a character array to int

Hi,

I have character array and i need to convert the content to int.

program snipet:

char array[10] = {"1","2","3","4","5","6","7","8","9"}.

I need to to extract each of these array fields and store them into an integer variable.

Casting the contents to (int), gives the ascii value of the array fields but not the actual value.

atoi function doesnt work here as it expects a const char*.

Any help would be appreciated.

Jyoti

A snippet to get you started:



    char a = '0';
    switch (a)
    {
    case '0': 
        value = 0;
        break;
    default: 
       /* non-numeric value */
    }

char datatype is treated as a limited range int (-127 to 127) by the compiler.

int i=0;
int irray[10]={0};
char array[10] = {'0','1','2','3','4','5','6','7','8','9'};  <- use ' not "
for(i=0;i<10;i++)
    irray=array;

Assuming you use the correct syntax: char array[10] = {'1','2','3','4','5','6','7','8','9'};
There is a relationship between the index of the array element and the value you need:
k=3;
chr=array[k];
ival=k+1;
Now chr would be '4' and ival would be 4. There is another trick that I've used from time to time:
ival = (int)chr - (int)'0';
It assumes ascii or some other character set that behaves this way. But I have used it anyway.

jim, i tried the code you've posted, its printing out the ascii values of the numbers (48, 49, and so on).

Won't this be as simple?

#include<stdio.h>

int main(void) {
        char a[]={'0','1','2','3','4','5','6','7','8','9'};
        int b[10];
        int i;
        for(i=0;i<10;i++) {
                b=(int)(a-48);
        }
}

I think that's what Perderabo has done...

It is indeed, he just didn't hardcode the value for '0', so any character set where the numbers ascend sequential will work.