views:

537

answers:

3

How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array

I have tried

char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0]; 
int temp2 = temp - 0;
b[0] = temp2;

I want 4 but it gives me ascii value 52

Also doing

a[0] = aoti(temp);

gives me error: invalid conversion from ‘char’ to ‘const char*’ initializing argument 1 of ‘int atoi(const char*)’

+7  A: 

You need to do:

int temp2 = temp - '0';

instead.

Gonzalo
From a language-lawyer standpoint I'd imagine it's not valid to assume that the digits are sequential, so this might not be 100% portable -- although it works in both ASCII (and its extensions) and EBCDIC, so in practice it's fine.
Captain Segfault
Surprisingly enough, it's perfectly fine even to a language lawyer - ISO C90 contains the following inconspicuous requirement: "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous".
Pavel Minaev
Very good, @Pavel. There's a lot of code written assuming that the alphas are also contiguous, which makes it a royal PITA to port to the mainframe's UNIX subsystem (USS, which use EBCDIC, not to be confused with zLinux which uses ASCII). Other than the rather limited minimal character set and the contiguous nature of the numeric characters, ISO C doesn't really mandate much in that area.
paxdiablo
+1  A: 

The atoi() version isn't working because atoi() operates on strings, not individual characters. So this would work:

char a[] = "4";
b[0] = atoi(a);

Note that you may be tempted to do: atoi(&temp) but this would not work, as &temp doesn't point to a null-terminated string.

Dave S.
A: 

You can replace the whole sequence:

char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0]; 
int temp2 = temp - 0;
b[0] = temp2;

with the simpler:

char a[] = "4x^0";
int b = new int[10];
b[0] = a[0] - '0';

No need at all to mess about with temporary variables. The reason you need to use '0' instead of 0 is because the former is the character '0' which has a value of 48, rather than the value 0.

paxdiablo