sprintf() Write formatted output to a character array
sprintf() Write formatted output to a character array
sprintf() formats text into an array and appends a null terminator excluded from its count. It has no capacity limit; ensure it fits or use snprintf().
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int sprintf(char *str, const char *format, ...);
⚙️ Parameters
| str Required | A pointer to a writable array large enough for the result and its terminating null character. |
|---|---|
| format Required | A format string defining the output text and conversions. |
| ... Optional | Variable arguments corresponding to the conversion specifiers. |
Returns: Returns the number of characters written, excluding the automatically appended null character, or a negative value if an encoding error occurs.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Item: Pencil, quantity: 12
⚠️ Warning sprintf() has no buffer-capacity argument. If the result is too long, it overflows the array and causes undefined behavior. Ensure the destination is large enough; where C99 is available, consider snprintf().
💡 Tip The result includes a terminating null character, so the required capacity is the visible character count plus one.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QHow can I prevent buffer overflow when using sprintf?
AEstimate the maximum output of every conversion, reserve space for the null character, and bound external string lengths. If safety cannot be established, do not use an unbounded sprintf call.
QDoes the sprintf return value include the terminating null character?
ANo. It counts only the generated characters; the array still needs one extra byte for the terminating null character.
QWhat is the difference between sprintf and snprintf, and which should I choose?
Asprintf takes no destination capacity and overflows if the result is too long. C99 snprintf accepts the buffer size, including the terminator, and truncates when space is insufficient. Its return value is the number of characters that would have been generated without the limit, so use it to detect truncation. When C99 is available, prefer snprintf for uncontrolled lengths.