我正在寻找一个sprintf() - 类似于自动分配所需内存的函数的实现.所以我想说
char* my_str = dynamic_sprintf( "Hello %s, this is a %.*s nice %05d string", a, b, c, d );
Run Code Online (Sandbox Code Playgroud)
和my_str检索保存此sprintf()结果的已分配内存的地址.
在另一个论坛中,我读到这可以像这样解决:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char* ret;
char* a = "Hello";
char* b = "World";
int c = 123;
int numbytes;
numbytes = sprintf( (char*)NULL, "%s %d %s!", a, c, b );
printf( "numbytes = %d", numbytes );
ret = (char*)malloc( ( numbytes + 1 ) * sizeof( char ) );
sprintf( ret, …Run Code Online (Sandbox Code Playgroud)