gpt4 book ai didi

c - 是 snprintf(NULL,0,...);行为规范?

转载 作者:太空狗 更新时间:2023-10-29 16:48:24 26 4
gpt4 key购买 nike

在 Linux 上,它返回要打印的字符数。

这是标准化行为吗?

最佳答案

是的。

来自 7.21.6.5 snprintf 函数,N1570(C11 草案):

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

这是一种查找未知数据长度的有用方法,您可以先找到所需的长度,然后再分配准确的内存量。一个典型的用例是:

char *p;

int len = snprintf(0, 0, "%s %s some_long_string_here_", str1, str2);

p = malloc(len + 1);

snprintf(p, len + 1, "%s %s some_long_string_here", str1, str2);

关于c - 是 snprintf(NULL,0,...);行为规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35035982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com