asprintf()在不确定字符串的长度时,能够根据格式化的字符串长度,申请足够的内存空间,使用后需自行使用free释放内存。
#include "stdio.h"
#include "malloc.h"
void main(void)
{
char *path;
if (asprintf(&path, "/root" "/%s", "test") < 0)
{
printf("error\n");
return;
}
printf("%s\n",path);
free(path);
return;
}
参考
ChatGPT
在C语言中,`asprintf` 函数是一种动态分配内存并创建新的字符串的方式。它是标准 printf 函数族的一部分