c - “%1$d” 输出的含义是什么?

标签 c ubuntu

<分区>

我正在使用 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/

相关文章:

在数组的子集上调用 qsort

c++ - 通过套接字传输大型阵列的最快方法

c - 是代码块错误吗?

postgresql - Docker,在包含 "ubuntu:14.04"的容器中安装 postgresql,离开容器时丢失

c - 指针和递归有问题

c - C语言中使用数组的Eratosthenes筛法

macos - Cron 作业未执行具有命令以作为另一个用户执行的 Shell 脚本

apache - 在 ubuntu 上部署 Laravel

ubuntu - 显示 Nginx 页面而不是主页(Digital Ocean - LEMP)

mysql - 错误 1130 (HY000) : Host '' is not allowed to connect to this MySQL server