ProgrammingVery hardProduct company OA

What is printed?

What is printed?
char buf[32], *p = buf;
for (int i = 1; i <= 4; i++) p += sprintf(p, "%d,", i * i);
p[-1] = '\0';
printf("%s %td", buf, p - buf);
  1. A. 1,4,9 9
  2. B. 1,4,9,16 9
  3. C. 1,4,9,16 8
  4. D. 1,4,9,16 10

Correct answer: B. 1,4,9,16 9

sprintf returns the number of characters it wrote, so p advances past "1,", "4,", "9," and "16,": 2 + 2 + 2 + 3 = 9. p[-1] overwrites the last comma with '\0', trimming the string, but p itself stays 9 bytes in.

More C Programming questions

Exams that ask this topic