-7

I don't know how this code is working?

#include<stdio.h>

 int main()
 {
     char *s = "PRO coder";
     int n = 7;
     printf("%.*s", n, s);
     return 0;
 }

The result I am getting is "PRO cod"

  • 3
    Yep, it's definitely working as it ought to. You might want to take a look at the manual pages for printf and format strings. Specifically, how to specify the precision (or in this case, the number of characters/numbers to print). – David Hoelzer Jul 15 '19 at 02:44
  • 1
    This section has an amost identical example: https://en.wikipedia.org/wiki/Printf_format_string#Precision_field – Jerry Jeremiah Jul 15 '19 at 02:46
  • Also look at this: https://stackoverflow.com/questions/1478115/printf-seems-to-be-ignoring-string-precision – Jerry Jeremiah Jul 15 '19 at 02:47
  • And the answer in https://stackoverflow.com/questions/23776824/what-is-the-meaning-of-s-in-a-printf-format-string describes how to think about it really well. – Jerry Jeremiah Jul 15 '19 at 02:49

1 Answers1

5

printf format string %.*s takes two arguments, * for the number and finally s for a string, so it prints the first 7 characters of the string pointer s. In general, anytime there is a number, you may use * instead to read it as an argument.

%7s would print seven characters or more if the string were longer, while %.7s would print up to seven characters. So sometimes one would write "%*.*s", 7, 7, s to print exactly 7 characters.

Joshua
  • 40,822
  • 8
  • 72
  • 132