I have been attacking atoi from several different angles trying to extract ints from a string 1 digit at a time.
Problem 1 - Sizing the array
Should this array of 50 chars be of size 50 or 51 (to account for null terminator)?
char fiftyNumbersOne[51] = "37107287533902102798797998220837590246510135740250";
Problem 2 - atoi output
What am I doing wrong here?
char fiftyNumbersOne[51] = "37107287533902102798797998220837590246510135740250";
int one = 0;
char aChar = fiftyNumbersOne[48];
printf("%c\n",aChar);//outputs 5 (second to last #)
one = atoi(&aChar);
printf("%d\n",one);//outputs what appears to be INT_MAX...I want 5
Problem 1
The array should be length 51. But you can avoid having to manually figure that out by simply doing char fiftyNumbersOne[] = "blahblahblah";
.
Problem 2
aChar
is not a pointer to the original string; it's just an isolated char
floating about in memory somewhere. But atoi(&aChar)
is treating it as if it were a pointer to a null-terminated string. It's simply walking through memory until it happens to find a 0
somewhere, and then interpreting everything it's found as a string.
You probably want:
one = aChar - '0';
This relies on the fact that the character values for 0
to 9
are guaranteed to be contiguous.