[英]concatenating strings and snprintf in c
我想知道这是否是concatenate
和NUL
终止包含宽度的字符串的正确方法。
#define FOO "foo"
const char *bar = "bar";
int n = 10;
float f = 10.2;
char *s;
int l;
l = snprintf (NULL, 0, "%-6s %-10s %4d %4f",FOO, bar, n, f);
s = malloc (l + 4); // should it be the number of formats tags?
if (s == null) return 1;
sprintf (s, "%-6s %-10s %4d %4f", FOO, bar, n, f);
很少有系统在其标准C库中具有asprintf
函数,该函数完全可以执行您在此处所做的事情:allocate和sprintf
。
您只需要向snprintf()
返回的值加1
,因为仅添加了一个空终止符。
但是,您确实需要检查l == -1
(指示snprintf()
失败)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.