Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using snprintf to print an array? Alternatives?

Tags:

c

printf

Is it at all possible to use snprintf to print an array? I know that it can take multiple arguments, and it expects at least as many as your formatting string suggests, but if I just give it 1 formatting string and an array of values, will it print the entire array to the buffer?

The reason I ask, is because I am modifying source code, and the current implementation only supported one value being placed in a string, but I am modifying it to support an array of values. I want to change the original implementation as little as possible.

If this doesn't work, is there another way someone would recommend to do this? Should I just suck it up and use a for loop (how well would that really work without stringbuffers)?

Essentially: What would be the best way to get all of the values from an array of doubles into the same string for a return?

like image 261
Nealon Avatar asked Jun 05 '13 13:06

Nealon


People also ask

What is the difference between Sprintf and Snprintf?

The snprintf function is similar to sprintf , except that the size argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least size characters for the string s .

Is Snprintf safe from buffer overflow?

It is safe as you long as you provide the correct length for the buffer.

What does snprintf return in c?

The snprintf() function returns the number of characters or values that have been written or stored for a sufficiently large buffer without including the null terminating character. And if the written characters are larger than the buffer size, it returns a negative value.

How do I concatenate strings using Snprintf?

If you must use snprintf , you will need to create a separate pointer to keep track of the end of the string. This pointer will be the first argument that you pass to snprintf . Your current code always uses buf , which means that it will always print to the beginning of that array.


1 Answers

No, there's no formatting specifier for that.

Sure, use a loop. You can use snprintf() to print each double after the one before it, so you never need to copy the strings around:

double a[] = { 1, 2, 3 };
char outbuf[128], *put = outbuf;

for(int = 0; i < sizeof a / sizeof *a; ++i)
{
  put += snprintf(put, sizeof outbuf - (put - outbuf), "%f ", a[i]);
}

The above is untested, but you get the general idea. It separates each number with a single space, and also emits a trailing space which might be annoying.

It does not do a lot to protect itself against buffer overflow, generally for code like this you can know the range of the inputs and make sure the outbuf is big enough. For production code you would need to think about this of course, the point here is to show how to solve the core problem.

like image 195
unwind Avatar answered Oct 28 '22 21:10

unwind