I'm trying to implement atoi function in C. However, whenever i use a test string "856" the resulting int will be 855. I tried many test cases but the outcome will be the same (e.g "4756"->4755). Below code is my incorrect solution.
#include <math.h>
#include <stdio.h>
int count = 0;
void atoi(char * str){
static int power = 0;
char * next = str;
next++;
if(*next != '\0' && next != NULL){
atoi(next);
power++;
//printf("%f\n",((*str) - '0') * pow(10, power));
count += ((*str) - '0') * pow(10, power);
}
else{
//printf("%f\n",((*str) - '0') * pow(10, power));
count += ((*str) - '0') * pow(10, power);
}
}
int main(){
char * string = (char *)malloc(sizeof(char)*3);
string = "457";
atoi(string);
printf("%d",count);
}
Could you please check why did this happen?