简体   繁体   中英

concatenating strings and snprintf in c

I'm wondering if this is the proper way to concatenate and NUL terminate strings including width.

#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

You only need to add 1 to the value returned by snprintf() , since there is only one null terminator added.

However, you do need to check for l == -1 (indicating that snprintf() failed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM