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[]) {
...
The only actual error is that you don’t check the return value of
mallocfor null.The name
itoais kind of already taken for a function that’s non-standard, but not that uncommon. It doesn’t allocate memory, rather it writes to a buffer provided by the caller:If you don’t want to rely on your platform having that, I would still advise following the pattern. String-handling functions which return newly allocated memory in C are generally more trouble than they’re worth in the long run, because most of the time you end up doing further manipulation, and so you have to free lots of intermediate results. For example, compare:
vs.
If you had reason to be especially concerned about performance (for instance if you’re implementing a stdlib-style library including
itoa), or if you were implementing bases thatsprintfdoesn’t support, then you might consider not callingsprintf. But if you want a base 10 string, then your first instinct was right. There’s absolutely nothing “incorrect” about the%dformat specifier.Here’s a possible implementation of
itoa, for base 10 only:Here’s one which incorporates the snprintf-style approach to buffer lengths: