intToStr recursively
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error intToStr recursively on this date .
This is a task from school, I am supposed to write a recursive function that will convert a given int to a string, I know I’m close but I can’t point the missing thing in my code, hints are welcome.
void intToStr(unsigned int num, char s[]) { if (num < 10) { s[0] = '0' + num; } else { intToStr(num/10, s); s[strlen(s)] = '0' + num%10; } }
Edit: my problem is that the function only works for pre initialized arrays, but if I let the function work on an uninitialized function it will not work.
Answer
Unless your array is zero-initialized, you are forgetting to append a null terminator when you modify it.
Just add it right after the last character:
void intToStr(unsigned int num, char s[]) { if (num < 10) { s[0] = '0' + num; s[1] = 0; } else { intToStr(num/10, s); s[strlen(s)+1] = 0; //you have to do this operation here, before you overwrite the null terminator s[strlen(s)] = '0' + num%10; } }
Also, your function is assuming that s has enough space to hold all the digits, so you better make sure it does (INT_MAX is 10 digits long I think, so you need at least 11 characters).