Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does %*d mean one or more integer?

Tags:

c

Does %*d mean one or more integer? in sprintf function

like image 302
Josh Morrison Avatar asked Jul 30 '26 22:07

Josh Morrison


2 Answers

It is used to manipulate the minimum width of the numerical value printed, and it specifically means that the width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. In other words, if you wanted to use a width that was stored in a variable, you could do this:

int width = /* something */;
printf("%*d", width, value);

EDIT: Oops! Correct syntax for sprintf is:

sprintf(buffer, "%*d", width, value);
like image 66
Jollymorphic Avatar answered Aug 01 '26 11:08

Jollymorphic


In the case of sprintf, it means you'll pass two integers, one specifies the field width, and the other the value you're going to convert.

IOW:

sprintf(buffer, "%5d", value);

is essentially the same as:

sprintf(buffer, "%*d", 5, value);

Much like when you're passing values as widths as literals in the format string, you can specify both a width and a precision if you want, something like this:

sprintf(buffer, "%*.*d", 5, 2, value);

It's also worth noting that with scanf and company, a "*" in the format string has a completely different meaning (to convert some input, but not assign the result to anything).

like image 45
Jerry Coffin Avatar answered Aug 01 '26 12:08

Jerry Coffin