I’m much less experienced in C than I am in higher-level languages. At Cisco, we use C, and I sometimes run into something that would be easy to do in Java or Python, but very difficult to do in C. Now is one of those times.
I have a dynamically-allocated array of unsigned integers which I need to convert to a comma-separated string for logging. While the integers are not likely to be very large, they could conceptually be anywhere from 0 to 4,294,967,295 In Python, that’s one short line.
my_str = ','.join(my_list)
How elegantly can people do this in C? I came up with a way, but it’s gross. If anyone knows a nice way to do it, please enlighten me.
Code now tested and builds under gcc.
In contrast to other answers, does not mandate C99.
The real problem here is not knowing the length of the string you’re going to need. Getting a number is as easy as
sprintf("%u", *num)usingnumto walk your array ofints, but how much space are you going to need? To avoid overrunning a buffer, you have to keep track of a lot of integers.Notice, that I keep track of how much of the buffer I have used and use
snprintfso I don’t overrun the end.snprintfwill tack on a\0, but since I’m usingbuf + writtenI will start at the\0of the previoussnprintf.In use:
Outputs:
Forcing the limiting to kick in, instead of overrunning:
Outputs, expectedly: