Some here are arguing that this approach is overkill, and for converting ints to strings I might be more inclined to agree. But when a reasonable bound for string size cannot be found, I have seen this approach used and have used it myself.
int size = snprintf(NULL, 0, "%d", 132);
char * a = malloc(size + 1);
sprintf(a, "%d", 132);
I'll break down what's going on here.
- On the first line, we want to determine how many characters we need. The first 2 arguments to
snprintf
tell it that I want to write 0 characters of the result to NULL
. When we do this, snprintf
won't actually write any characters anywhere, it will simply return the number of characters that would have been written. This is what we wanted.
- On the second line, we are dynamically allocating memory to a
char
pointer. Make sure and add 1 to the required size (for the trailing
terminating character).
- Now that there is enough memory allocated to the
char
pointer, we can safely use sprintf
to write the integer to the char
pointer.
Of course you can make it more concise if you want.
char * a = malloc(snprintf(NULL, 0, "%d", 132) + 1);
sprintf(a, "%d", 132);
Unless this is a "quick and dirty" program, you always want to make sure to free the memory you called with malloc
. This is where the dynamic approach gets complicated with C. However, IMHO, if you don't want to be allocating huge char
pointers when most of the time you will only be using a very small portion of them, then I don't think this is bad approach.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…