I was wondering if my implementation of an "itoa" function is correct. Maybe you can help me getting it a bit more "correct", I'm pretty sure I'm missing something. (Maybe there is already a library doing the conversion the way I want it to do, but... couldn't find any)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char * itoa(int i) {
char * res = malloc(8*sizeof(int));
sprintf(res, "%d", i);
return res;
}
int main(int argc, char *argv[]) {
...
i found an interesting resource dealing with several different issues with the itoa implementation
you might wanna look it up too
itoa() implementations with performance tests
There a couple of suggestions I might make. You can use a static buffer and strdup to avoid repeatedly allocating too much memory on subsequent calls. I would also add some error checking.
If this will be called in a multithreaded environment, remove "static" from the buffer declaration.
A good
int
to string oritoa()
has these properties;[INT_MIN...INT_MAX]
, base[2...36]
without buffer overflow.int
size.unsigned
to have a greater positive range thanint
. In other words, does not useunsigned
.'-'
for negative numbers, even whenbase != 10
.Tailor the error handling as needed. (needs C99 or later):
I'm not quite sure where you get
8*sizeof(int)
as the maximum possible number of characters --ceil(8 / (log(10) / log(2)))
yields a multiplier of3*
. Additionally, under C99 and some older POSIX platforms you can create an accurately-allocating version withsprintf()
:HTH