L
Lax
Here is my 1st attempt at the solution for K&R2 Exercise 4-12:
void itoa(int n, char *s)
{
if (n < 0)
{
*s++ = '-';
n = -n;
}
if( n/10 > 0 )
itoa( n/10, s );
*s++ = n%10 + '0';
*s = 0;
}
I realize why my code is not working, it's because the increments
don't carry forward when the recursive calls "unwind."
I can solve this this way:
void itoa2(int n, char *s)
{
static char *p = 0;
if(p == 0)
p = s;
if (n < 0)
{
*p++ = '-';
n = -n;
}
if( n/10 > 0 )
itoa2( n/10, p );
*p++ = n%10 + '0';
*p = 0;
}
This keeps the p pointer up-to-date while the recursive calls unwind.
My quesiton is, does anyone know of a solution that doesn't require
the introduction of a static duration variable? Something like a small
modifcation to my first attempt?
void itoa(int n, char *s)
{
if (n < 0)
{
*s++ = '-';
n = -n;
}
if( n/10 > 0 )
itoa( n/10, s );
*s++ = n%10 + '0';
*s = 0;
}
I realize why my code is not working, it's because the increments
don't carry forward when the recursive calls "unwind."
I can solve this this way:
void itoa2(int n, char *s)
{
static char *p = 0;
if(p == 0)
p = s;
if (n < 0)
{
*p++ = '-';
n = -n;
}
if( n/10 > 0 )
itoa2( n/10, p );
*p++ = n%10 + '0';
*p = 0;
}
This keeps the p pointer up-to-date while the recursive calls unwind.
My quesiton is, does anyone know of a solution that doesn't require
the introduction of a static duration variable? Something like a small
modifcation to my first attempt?