Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!garfield!matthew1 From: matthew1@garfield.cs.mun.ca (Matthew J. Newhook) Newsgroups: comp.lang.c Subject: Re: New 'n' Improved comp.lang.c FAQ List Message-ID: <1991Apr4.024300.19969@garfield.cs.mun.ca> Date: 4 Apr 91 02:43:00 GMT References: <910401.0xf001@etiquette.uu.net> <1991Apr1.203024.19679@unlv.edu> <31946@shamash.cdc.com> Organization: CS Department, Memorial University of Newfoundland Lines: 66 bls@u02.svl.cdc.com (Brian Scearce) writes: >grover@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 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@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