What does "%.*s" mean in printf?

Shaobo Wang picture Shaobo Wang · Oct 26, 2011 · Viewed 89k times · Source

I got a code snippet in which there is a

printf("%.*s\n")

what does the %.*s mean?

Answer

AusCBloke picture AusCBloke · Oct 26, 2011

You can use an asterisk (*) to pass the width specifier/precision to printf(), rather than hard coding it into the format string, i.e.

void f(const char *str, int str_len)
{
  printf("%.*s\n", str_len, str);
}