[英]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". 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". Why does this happen?为什么会这样?
Why does this happen?
为什么会这样?
Navigating via a list of variable arguments of different types is hard.通过不同类型的变量 arguments 的列表导航很困难。 The requirement of
printf
is that you have to give a format specifier for all arguments. printf
的要求是您必须为所有 arguments 提供格式说明符。 (In reality, you have to give format specifications for the initial part of all arguments up to the maximum <num>$
argument you requested). (实际上,您必须为所有 arguments 的初始部分提供格式规范,直到您请求的最大
<num>$
参数)。
When printf
is navigating arguments, it has to know what type to use to "jump" over to the next argument - va_arg(va, int)
?当
printf
导航 arguments 时,它必须知道使用什么类型“跳转”到下一个参数 - va_arg(va, int)
? va_arg(va, long)
? va_arg(va, long)
? va_arg(va, char)
? va_arg(va, char)
? For printf
to know, you have to give all format specifiers for all arguments.要知道
printf
,您必须为所有 arguments 提供所有格式说明符。 For example, to get to the 3$
, printf
walks thought format string, finds the first %1$
part in format string, extracts the type c
, and does va_arg(char)
, then it has to walk over format string again, find the %2$
part, extract its type c
, and then it knows to do va_arg(char)
, and repeats for all arguments until it finally can get to the 3$
type requested to print.例如,要获取
3$
, printf
格式字符串,找到格式字符串中的第一个%1$
部分,提取类型c
,然后执行va_arg(char)
,然后它必须再次遍历格式字符串,找到%2$
部分,提取其类型c
,然后它知道要执行va_arg(char)
,并对所有 arguments 重复,直到它最终可以到达请求打印的3$
类型。
If one of the specifications is missing, printf
doesn't know how to jump over elements in va_list
to get to the element requested to print.如果缺少其中一项规范,
printf
不知道如何跳过va_list
中的元素以到达请求打印的元素。 So it fails.所以它失败了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.