c - comp.lang.c 常见问题解答中有错误?计算可变格式字符串的长度

标签 c string variadic-functions strlen

问题 15.4:varargs/varargs1.html

在示例代码中,他们似乎认为如果到达列表末尾,则 ‍‍‍va_arg 返回 NULL:

len = strlen(first);

va_start(argp, first);

while((p = va_arg(argp, char *)) != NULL)
    len += strlen(p);

va_end(argp);

但是 va_arg 的文档明确指出情况并非如此,并且 va_arg 会很高兴地越过列表的末尾。

这与我尝试模仿上述代码并因此出现段错误的经验一致。

最佳答案

事实上,va_arg 没有提到在列表的第 nd 处返回 NULL

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

但常见问题解答说:

A call to vstrcat looks something like

char *str = vstrcat("Hello, ", "world!", (char *)NULL);

这意味着他们假设调用者将传递 NULL 作为最后一个参数来表示列表结束

关于c - comp.lang.c 常见问题解答中有错误?计算可变格式字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479621/

相关文章:

c - 在 sprintf() 之前解析并替换 NaN 值

c - 解析参数时更改值

c - 如何使结构体指向不同的字符串?

Java:在字符串变量中累积输出模式?

maven - 当将null作为varargs参数发送时,Gradle和Maven的行为不同

scala:如何将扩展列表作为可变参数传递到方法中?

C 计算器,有很多函数 in 函数 in 函数

c - 如何使用 strcmp 对 2d char 数组的行(字符串)进行排序?

C:非 ASCII 文本数据的 char 与 unsigned char

string - 你怎么能在低级别对字符串单词进行排序?