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().

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

int sprintf(char *str, const char *format, ...);

⚙️ Parameters

str RequiredA pointer to a writable array large enough for the result and its terminating null character.
format RequiredA format string defining the output text and conversions.
... OptionalVariable 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏