问题描述
什么是%* d
?我知道%d
用于 integers
,所以我认为%* d
还必须仅与整数相关?目的是什么?它是做什么的?
What is %*d
? I know that %d
is used for integers
, so I think %*d
also must related to integer only? What is the purpose of it? What does it do?
int a=10,b=20;
printf("\n%d%d",a,b);
printf("\n%*d%*d",a,b);
结果是
10 20
1775 1775
推荐答案
printf
中的%* d
允许您使用变量按照以下方式控制字段宽度:
The %*d
in a printf
allows you to use a variable to control the field width, along the lines of:
int wid = 4;
printf ("%*d\n", wid, 42);
这将为您提供:
..42
(其中每个.
字符均为空格). *
使用一个参数 wid
,而 d
使用 42
.
(with each of those .
characters being a space). The *
consumes one argument wid
and the d
consumes the 42
.
您拥有的表单,例如:
printf ("%*d %*d\n", a, b);
按照标准,
是未定义的行为,因为您应该在格式字符串之后提供四个参数,而不是两个(并且类似 gcc
这样的好的编译器会告诉您有关此问题的信息)如果您提高了警告级别).从 C11 7.20.6格式化的输入/输出功能
:
is undefined behaviour as per the standard, since you should be providing four arguments after the format string, not two (and good compilers like gcc
will tell you about this if you bump up the warning level). From C11 7.20.6 Formatted input/output functions
:
应该是这样的:
printf ("%*d %*d\n", 4, a, 4, b);
得到奇怪输出的原因是由于未定义的行为.这非常好答案向您展示了当您不遵守规则(尤其是与这种情况有关)时可能会出错(以及为什么)的事情.
And the reason you're getting the weird output is due to that undefined behaviour. This excellent answer shows you the sort of things that can go wrong (and why) when you don't follow the rules, especially pertaining to this situation.
现在我不希望这是一个对齐问题,因为您对所有数据类型都使用了 int
,但是与所有未定义的行为一样,任何事情都可能发生
Now I wouldn't expect this to be a misalignment issue since you're using int
for all data types but, as with all undefined behaviour, anything can happen.
这篇关于C语言中的%d和%* d有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!