Defined in header <stdio.h> | ||
int asprintf(char**restrict strp,constchar*restrict fmt, ...); | (1) | (dynamic memory TR) |
int aswprintf(wchar_t**restrict strp,constwchar_t*restrict fmt, ...); | (2) | (dynamic memory TR) |
int vasprintf(char**restrict strp,constchar*restrict fmt, va_list arg); | (3) | (dynamic memory TR) |
int vaswprintf(wchar_t**restrict strp,constwchar_t*restrict fmt, va_list arg); | (4) | (dynamic memory TR) |
arg, which shall be initialized by theva_start macro (and possibly subsequentva_arg calls).Contents |
| strp | - | A pointer to achar* orwchar_t* which will contain the formatted output |
| fmt | - | A format string as withprintf/wprintf and related functions |
| arg | - | Any extra arguments are used as withvsprintf andvswprintf |
The number of characters written, just likesprintf(1),swprintf(2),vsprintf(3), orvswprintf(4), respectively. If memory allocation wasn't possible, or some other error occurs, these functions will return-1, and the contents ofstrp is undefined.
These functions are GNU extensions, not in C or POSIX. They are also available under *BSD. The FreeBSD implementation setsstrp toNULL on error.
Thevasprintf andvaswprintf functions do not invoke theva_end macro.
Can be tested with clang (C11)
#include <stdio.h>#include <stdlib.h>#include <stdarg.h> void test(constchar*fmt, ...){char* dyn_buf; printf("Demo asprintf:\n");constint written_1= asprintf(&dyn_buf,"%s", fmt);printf("dyn_buf:\"%s\"; %i chars were written\n", dyn_buf, written_1);free(dyn_buf); printf("Demo vasprintf:\n"); va_list args; va_start(args, fmt);constint written_2= vasprintf(&dyn_buf, fmt, args); va_end(args);printf("dyn_buf:\"%s\"; %i chars were written\n", dyn_buf, written_2);free(dyn_buf);} int main(void){ test("Testing... %d, %d, %d",1,2,3);}
Output:
Demo asprintf:dyn_buf: "Testing... %d, %d, %d"; 21 chars were writtenDemo vasprintf:dyn_buf: "Testing... 1, 2, 3"; 18 chars were written