作者:孩子气zyj2 | 来源:互联网 | 2023-05-17 19:39
Whatis%*d?Iknowthat%disusedforintegers,soIthink%*dalsomustrelatedtointegeronly?
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?
% * d是什么?我知道%d是用于整数的,所以我认为%*d也只能与整数有关?它的目的是什么?它做什么?
int a=10,b=20;
printf("\n%d%d",a,b);
printf("\n%*d%*d",a,b);
Result is
结果是
10 20
1775 1775
3 个解决方案
17
The %*d
in a printf
allows you to use a variable to control the field width, along the lines of:
printf中的%*d允许您使用一个变量来控制字段宽度:
int wid = 4;
printf ("%*d\n", wid, 42);
which will give you:
这将给你:
..42
(with each of those .
characters being a space). The *
consumes one argument wid
and the d
consumes the 42
.
(每个都有。字符作为一个空间)。*消耗一个参数wid,而d消耗42。
The form you have, like:
你的表格,比如:
printf ("%*d %*d\n", a, b);
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
:
是按照标准的未定义的行为,因为您应该在格式化字符串之后提供4个参数,而不是两个(如果您提高了警告级别,像gcc这样好的编译器会告诉您这一点)。从C11 7.20.6格式化输入/输出函数:
If there are insufficient arguments for the format, the behavior is undefined.
如果对格式没有足够的参数,则行为是未定义的。
It should be something like:
应该是这样的:
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.
你得到奇怪输出的原因是由于未定义的行为。这个优秀的回答会告诉你,当你不遵守规则时,会出现什么问题(以及为什么),尤其是在这种情况下。
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.
现在,我不希望这是一个错误对齐的问题,因为您在所有数据类型中都使用int,但是,和所有未定义的行为一样,任何事情都可能发生。