2
printf("%s%d%c", s, a, c);

The string would be printed on the stdout; but how the implementation knows to define what size of the char array to hold result?

Or the alternative way is: use the fixed size buffer, handle each variable argument behind the format string, if the interpreted string size exceed the buffer size, then output it to output stream. Is this true?

By the way, I think, the string type in C++, its implementation uses the heap memory, dynamic memory allocator, just as new, or delete, is this correct?

Puppy
  • 144,682
  • 38
  • 256
  • 465
bluesea
  • 429
  • 4
  • 9

3 Answers3

4

The string would be printed on the stdout

That's correct. Which is a stream, no char[] is required. Only sprintf() would require a guess at a string buffer size.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 4
    The last sentence is *slightly* misleading since `sprintf` doesn’t take care of the buffer itself. The *caller* needs to know how large the buffer is. Of course they never do, they just use a fixed-size buffer. :p – Konrad Rudolph Jul 08 '12 at 17:11
  • Thanks for your answer. So Am I right about c++ string implementation, that the string is implemented as heap allocated memory by new/delete? – bluesea Jul 08 '12 at 17:14
  • The std::string class is a library implementation detail, every compiler has its own library. Mine doesn't start using the heap until the string gets large enough. This otherwise has nothing to do with printf(), maybe you ought to ask another question about it. – Hans Passant Jul 08 '12 at 17:33
1

As other people have explained, printf doesn't need to know the size of some output buffer ahead of time because it doesn't need to allocate one when writing to a FILE* stream.

However, you might then wonder: what about functions in the printf-family that don't write to FILE* streams? What about, say, the non-standard asprintf function that returns an allocated string?

The underlying implementation for the printf family of functions can do a dry-run. That is, it can simulate doing the operation without actually writing to memory and keep track of the number of chars that it would have written. Once it computes the that number, it then can allocate a buffer of the appropriate size and repeat the operation for real. This is what a caller would do when it needs to allocate a buffer itself, such as when calling snprintf.

(You also talk about buffered I/O. While printf can use that, printf doesn't necessarily know about the buffer itself (and it probably shouldn't). You can think of it as calling fputc a bunch of times, which then writes the char to some buffer, flushing it if it's full.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

but how the implementation knows to define what size of the char array to hold result

Just reads up to null terminating byte '\0'. No need to explicitely know the size of the "%s%d%c" which is passed in as a char *

Cratylus
  • 52,998
  • 69
  • 209
  • 339