What is the difference between %d and %*d in c language?

无人久伴 提交于 2021-02-18 10:50:29

问题


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);

Result is

10 20 
1775 1775 

回答1:


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);

which will give you:

..42

(with each of those . characters being a space). The * consumes one argument wid and the d consumes the 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:

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.




回答2:


When used with scanf() functions, it means that an integer is parsed, but the result is not stored anywhere.

When used with printf() functions, it means the width argument is specified by the next format argument.




回答3:


The * is used as an indication that the width is passed as a parameter of printf




回答4:


in "%*d", the first argument is defined as the total width of the output, the second argument is taken as normal integer. for the below program

int x=6,p=10;
printf("%*d",x,p);
output: "    10"

the first argument ta passed for *, that defines the total width of the output... in this case, width is passed as 6. so the length of the entire output will be 5. now to the number 10, two places are required (1 and 0, total 2). so remaining 5-2=3 empty string or '\0' or NULL character will be concatenated before the actual output



来源:https://stackoverflow.com/questions/9937052/what-is-the-difference-between-d-and-d-in-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!