I got a code snippet in which there is a statement
printf("%*.*s");
what does the %*.*s
mean?
The code is
char *c="**********";
int i,n=4;
for(i=1;i<=n;i++)
{
printf("%*.*s\n",i,i,c);
}
Output is:
*
**
***
****
I got a code snippet in which there is a statement
printf("%*.*s");
what does the %*.*s
mean?
The code is
char *c="**********";
int i,n=4;
for(i=1;i<=n;i++)
{
printf("%*.*s\n",i,i,c);
}
Output is:
*
**
***
****
To start with, first let me clarify, the *
s in the format string here are not for printing *
charcater(s) itself. They do have a special meaning in this context.
In your case,
printf("%*.*s");
the first *
is the field width, the second *
one (to be precise, .*
) denotes precision.
Both the *
s need an int
argument to supply the respective value.
To quote the standard,
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an
int
argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
So, a generic form for a conversion specifier to appear is
%[flags]<field width><precision><length modifier>[conversion specifier character]
Please note all the elements in <>
are optional, only [flags]
and [conversion specifier character]
are mandatory. That said, the requirement says
Zero or more flags
thus, essentially making [flags]
also as optional.
Please refer to C11
standard, chapter ยง7.21.6.1 for more info.
Read the spec of
printf
:For strings the width is Minimum number of characters to be printed (padding may be added).
For strings the precission is the Maximum number of characters to be printed.
Your program is not passing the required optional arguments (witdh, precission, the string to be printed). Behavior will be undefined (likely a crash).