在c中连接字符串和snprintf

发布于 2024-10-06 17:17:19 字数 380 浏览 0 评论 0原文

我想知道这是否是连接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);

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷︶言冷语的世界 2024-10-13 17:17:19

相当多的系统在其标准 C 库中都有一个函数 asprintf,它的功能与您在这里所做的完全一样:分配和 sprintf

Quite a few systems have a function asprintf in their standard C libraries that does exactly what you do here: allocate and sprintf.

温柔女人霸气范 2024-10-13 17:17:19

您只需将 1 添加到 snprintf() 返回的值中,因为只添加了一个空终止符。

但是,您确实需要检查 l == -1 (表明 snprintf() 失败)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文