Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

sprintf — formatting text into a buffer

sprintf writes formatted text into a char array. It takes no buffer size: storage must also accommodate the terminating '\0'.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdio.h>
int sprintf(char * restrict s, const char * restrict format, ...);

sprintf from <stdio.h> writes into s, not a stream. format specifies conversions: %s expects a string, %d an int, and %% writes %. Mismatched argument types cause undefined behavior.

Output ends with '\0'. The function returns the character count excluding this terminator, or a negative value for an encoding error.

An undersized buffer and copying between overlapping objects cause undefined behavior. Checking the return value cannot prevent overflow. snprintf accepts a size limit and allows truncation detection.

Examples

#include <stdio.h>

int main(void)
{
    char buffer[16];
    int count = sprintf(buffer, "%s=%d", "x", 42);
    if (count < 0) {
        return 1;
    }
    printf("%s\ncount=%d\n", buffer, count);
    return 0;
}

Result

x=42
count=4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources