我似乎记得,如果你打电话sprintf
给一个NULL
目的地,它不会做任何事情。但是,它确实返回了它“写入”的字符数。如果我是对的(而且我似乎找不到来源),那么你可以这样做:
// find the length of the string
int len = sprintf(NULL, fmt, var1, var2,...);
// allocate the necessary memory.
char *output = malloc(sizeof(char) * (len + 1)); // yes I know that sizeof(char) is defined as 1 but this seems nicer.
// now sprintf it after checking for errors
sprintf(output, fmt, var1, var2,...);
另一种选择是使用snprintf
它允许您限制输出的长度:
#define MAX 20 /* or whatever length you want */
char output[MAX];
snprintf(output, MAX, fmt, var1, var2,...);
snprintf
将缓冲区的大小作为参数,并且不允许输出字符串超过该大小。