New 'n' Improved comp.lang.c FAQ List

Matthew J. Newhook matthew1 at garfield.cs.mun.ca
Thu Apr 4 12:43:00 AEST 1991


bls at u02.svl.cdc.com (Brian Scearce) writes:

>grover at big-joe.cs.unlv.edu (Kevin Grover) writes:
>> Apparently non-obvious April Fool's Day bogus account posts:
>>> Q: Why doesn't this function work:
>>>
>>>         itoa(int i)
>>>         {
>>>         char retbuf[5];         /* biggest int: 32769 */
>>>         sprintf("%d", retbuf, i);
>>>         return retbuf;
>>>         }
>>>

>>    A correct version of this program is:
>>        char *itoa(int i)
>>          {
>>            static char retbuf[5];         /* biggest int: 32769 */
>>            sprintf(retbuf, "%d", i);
>>            return retbuf;
>>          }

>Almost, but not quite, Mr. Grover.  The *really* correct version of this:

>        char *itoa(int i)
>          {
>            static char retbuf[5];         /* biggest int: 32768 */
>            sprintf(retbuf, "%d", i);
>            return retbuf;
>          }

Actually here is a correct (portable) version (assuming that you want to 
keep a static character buffer, and not use a newly malloc'd one each time).

#include <math.h>

char *itoa(int i)
{
    static int first = 1;
    static char *s;

    if (first) { /* IF FIRST TIME ALLOCATE MEMORY FOR STRING */
        first = 0;
        s = (char *) 
        malloc((long) ceil(log10(pow(2, (double) sizeof(int) * 8))) +1);
        if (!s) {
            fprintf(stderr,"malloc failed\n");
            exit(1);
        }
    }

    sprintf(s, "%d", i);
    return s;
}

This is portable, 'cause it always assigns the correct value to the size of
the array, without depending on the sizeof(int) == 2.

Matthew Newhook
        

-- 
----------------matthew1 at garfield.cs.mun.ca 
"Living in the limelight; the universal dream for those who wish to 
seem. Those who wish to be must put aside the alienation, get on with 
the facination, the real relation, the underlying theme" - Rush



More information about the Comp.lang.c mailing list