There are two bugs in printd():
- The last character is an
linstead of a semicolon. - If
nis negative, it prints a negative sign before each digit.
Your itoa() also has a bug in handling negative input. It always stringifies the absolute value of n.
Your strategy to use the return value to determine which array element to write to seems like a good idea. I think it would be more user friendly, though, to returnsay that you are returning the strlen() of the output.
int itoa(int n, char s[]) {
int i = 0;
if (n < 0) {
s[0] = '-';
return 1 + itoa(-n, s + 1);
}
if (n / 10) {
i = itoa(n / 10, s);
}
s[i] = n % 10 + '0';
s[++i] = '\0';
return i; /* strlen(s), i.e. the next free slot in array */
}