繁体   English   中英

奇怪的 _printf_p 行为。 为什么会这样?

[英]Strange _printf_p behaviour. Why does this happen?

_printf_p ("%1$c\n", 'a', 'b', 'c');    // OK
_printf_p ("%2$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%3$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%1$c %2$c\n", 'a', 'b', 'c');    // OK
_printf_p ("%2$c %1$c\n", 'a', 'b', 'c');    // OK
_printf_p ("%1$c %3$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%3$c %1$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%2$c %3$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%3$c %2$c\n", 'a', 'b', 'c');    // Debug Assertion Failed
_printf_p ("%1$c %2$c %3$c\n", 'a', 'b', 'c');    // OK
_printf_p ("%3$c %2$c %1$c\n", 'a', 'b', 'c');    // OK
_printf_p ("%2$c %1$c %3$c\n", 'a', 'b', 'c');    // OK

If not all of the output arguments are used, function _printf_p will work only when continious positional arguments starting from 1$ are specified in the format string, otherwise it will emit error "Debug Assertion Failed". 为什么会这样?

为什么会这样?

通过不同类型的变量 arguments 的列表导航很困难。 printf的要求是您必须为所有 arguments 提供格式说明符。 (实际上,您必须为所有 arguments 的初始部分提供格式规范,直到您请求的最大<num>$参数)。

printf导航 arguments 时,它必须知道使用什么类型“跳转”到下一个参数 - va_arg(va, int) va_arg(va, long) ? va_arg(va, char) ? 要知道printf ,您必须为所有 arguments 提供所有格式说明符。 例如,要获取3$printf格式字符串,找到格式字符串中的第一个%1$部分,提取类型c ,然后执行va_arg(char) ,然后它必须再次遍历格式字符串,找到%2$部分,提取其类型c ,然后它知道要执行va_arg(char) ,并对所有 arguments 重复,直到它最终可以到达请求打印的3$类型。

如果缺少其中一项规范, printf不知道如何跳过va_list中的元素以到达请求打印的元素。 所以它失败了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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