c - Working with atoi -


i have been attacking atoi several different angles trying extract ints string 1 digit @ time.

problem 1 - sizing array
should array of 50 chars of size 50 or 51 (to account null terminator)?

char fiftynumbersone[51] = "37107287533902102798797998220837590246510135740250"; 

problem 2 - atoi output

what doing wrong here?

char fiftynumbersone[51] = "37107287533902102798797998220837590246510135740250"; int 1 = 0; char achar = fiftynumbersone[48]; printf("%c\n",achar);//outputs 5 (second last #) 1 = atoi(&achar); printf("%d\n",one);//outputs appears int_max...i want 5 

problem 1

the array should length 51. can avoid having manually figure out doing char fiftynumbersone[] = "blahblahblah";.

problem 2

achar not pointer original string; it's isolated char floating in memory somewhere. atoi(&achar) treating if pointer null-terminated string. it's walking through memory until happens find 0 somewhere, , interpreting it's found string.

you want:

one = achar - '0'; 

this relies on fact character values 0 9 guaranteed contiguous.


Comments