I’m relatively new to C and I’m curious why I’m having problems with atoi in this situation. I feel like I am not understanding something fundamental. Here is my sample code:
int main()
{
char last[3];
last[2]='\0';
uint16_t num1;
uint16_t num2;
// I read in num1 and num2 from a file and do an integer operation on them. bigarray is the file contents. bigarray[i] is a integer
num1=bigarray[i] - 1;
num2=bigarray[i+1] - 1;
last[0]=(char)num1;
last[1]=(char)num2;
printf("%i\n:", atoi(last));
}
When I print out last[0] and last[1] seperatly it gives me the correct values. When I print out atoi(last) then it gives me 0.
Why does atoi give me 0 in this situation, and how can I fix it?
atoiexpects ASCII characters, so if the array is, let’s saylast[0] = 1andlast[1] = 2, it will find no characters, if it waslast[0] = '1'andlast[1] = '2'than it would print12.In this particular case you can achieve that by:
(assuming
num1andnum2are between 0-9)Short edit to explain the idea:
The ascii values of the digits
'0'(0x30) to'9'(0x39) are sequential, so adding0to'0'(0x30) will give you'0'(0x30) and adding2to'0'(0x30) will give you'2'(0x32)