This one is in interivew: bi
char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}
static char retbuf[20];
This fix is imperfect, since a function using static data is not reentrant. Furthermore, successive calls to this version of itoa keep overwriting the same return buffer: the caller won't be able to call it several times and keep all the return values around simultaneously.
There are two better solution:
1. have the caller pass space for the result:char *itoa(int n, char *retbuf)
{
sprintf(retbuf, "%d", n);
return retbuf;
}
...
char str[20];
itoa(123, str);
char *itoa(int n)
{
char *retbuf = new char [20];
if(retbuf != NULL)
sprintf(retbuf, "%d", n);
return retbuf;
}
...
char *str = itoa(123);
delete []str;
No comments:
Post a Comment