<分区>
我正在使用 ubuntu 运行此代码。但是代码是什么意思?
运行 ubuntu 代码: gcc 名称.c -o 名称
/名字
#include <stdio.h>
int main(void)
{
printf("%d %1$d %2$d",5);
}
输出是“5 5 随机数”。那么,%2$d 是什么意思?
<分区>
我正在使用 ubuntu 运行此代码。但是代码是什么意思?
运行 ubuntu 代码: gcc 名称.c -o 名称
/名字
#include <stdio.h>
int main(void)
{
printf("%d %1$d %2$d",5);
}
输出是“5 5 随机数”。那么,%2$d 是什么意思?
最佳答案
1$
和2$
指定参数的位置。它仅由 POSIX 指定,不在 C 标准中。
根据 C 标准,这里 printf
的行为是未定义的,因为 $
不是有效的 printf
转换规范。
根据 fprintf posix :
[...] In format strings containing the "%n$" form of a conversion specification, a field width or precision may be indicated by the sequence "*m$", where m is a decimal integer in the range [1,{NL_ARGMAX}] giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision, for example:
printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);
所以:
printf("%d %1$d %2$d",5);
%d
- 指定下一个 int 参数应转换为带符号的十进制数。%1$d
- 指定格式字符串 int 参数后的 first 应转换为带符号的十进制%2$d
- 指定格式字符串 int 参数后的second 应转换为带符号的十进制您只为 printf
函数提供了两个参数(格式字符串和 5
)。结果未定义,因为 2$
需要另一个参数。
关于c - “%1$d” 输出的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56373241/