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:
*
**
***
****
Read the spec of printf
:
%[flags][width][.precision][length]specifier
s
String of characters
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
For strings the width is Minimum number of characters to be printed (padding may be added).
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
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).
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.
You need to pass 3 arguments for this statement as printf("%*.*s",a,b,str);
where a
and b
are integers and str
is string.
It prints out a
number of characters with first b
characters of str
as last b
characters of output. First b-a
characters will be space(' ').
.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
printf("%.*s\n", 20, "rabi");