Peter Hwang
Peter Hwang

Reputation: 991

Understanding printf function with * format

char **w = c->u.word;
printf ("%*s%s", indent, "", *w);

Ok, currently, *w holds "true" as a string value.
And I have no problem accessing it.
indent is integer value, which is 2.

First, I don't understand how printf function works in this case. It looks like it has four arguments. Second, I expected the output as 'true', but I got nothing. why does it behave like this?

Upvotes: 1

Views: 150

Answers (2)

Gangadhar
Gangadhar

Reputation: 10516

printf("%10s","Hello"); 

this will print hello with width 10 and it is Right aligned.

printf("%*s",10,"Hello");  //is same  as above 

printf ("%*s%s", indent, "", *w);

This will print indent number of spaces before printing string which is pointed by *w

Upvotes: 1

lurker
lurker

Reputation: 58244

The asterisk (*) means you can define a variable field width. So

"%*s%s"

Means you have a string with a variable field width (the length of the field is passed as an integer before the string is to printf). That is followed by a string which will be printed with no padding.

Your parameters are:

indent, "", *w

In the format, indent corresponds to the asterisk (*), "" corresponds to the s in the %*s, and *w corresponds do the %s. So this will print a zero-length string with a field width of indent followed by the string that *w points to. In other words, you'll always get indent spaces in front of the string *w in the output.

Upvotes: 5

Related Questions