What is vsprintf in C?

The vsprintf is defined in the stdio.h header file. It uses a format string and corresponding arguments to generate a string stored in the provided destination string. vsprintf is different from the normal sprintf because, instead of directly taking in arguments corresponding to the format string, it takes in a single variable list of arguments as input.

Syntax

The following is the syntax to declare the vsprintf function:

Parameters

The sprintf_s function takes in 3 arguments:

  • s: The pointer to the destination string where the formatted string will be stored

  • format: The pointer to the format string. This may include format specifiers like %s.

  • arglist: A variable list of arguments of type va_list. This data type is defined in the stdarg.h header file.

An object of type va_list needs to be initialized by the va_start macro and needs to be released after use through the va_end macro

Return value

vsprintf can return one of the two things:

  • Upon successful execution, it returns the number of items filled in the list of variable arguments given in the parameters.

  • If there is a failure during the assignment of arguments or while interpreting an input, or EOF (End Of File) is returned.

Example

The following is an example where we take two variables, one with the magnitude of the measurement and the other containing the units. For this example, we constructed a different function, get_store, that handles initializing and storage of the arglist. It also runs the vsprintf function to store the created string into the provided character array:

#include <stdio.h>
#include <stdarg.h>
// function to automatically initialize the list of arguments
void get_store ( char* dest_str, const char * format, ... )
{
// the arglist holds list of all arguments fed to this function
va_list arglist;
// initializing the arglish using the vs_start macro
va_start (arglist, format);
// putting the arguments into the arglist using vsprintf
vsprintf (dest_str, format, arglist);
// releasing the arglish variable using the va_end macro
va_end (arglist);
}
int main ()
{
// variable to store the final string into
char dest[40];
// variables whose data we use to form the final string
int magnitude = 500;
char unit[40] = "meters";
// sending format string and arguments to the get_store function
// this format string requires an input with first an integer folllowed by a string
get_store (dest, "The quantity is %d %s ", magnitude, unit);
//printing out the variables to check data in it
printf ("%s\n", dest);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved