C format strings, pointer arithmetic, and printf: what does this program print? #include<stdio.h> int main() { char *str; str = "%d "; str++; str++; printf(str-2, 300); return 0; }

Difficulty: Medium

Correct Answer: 300

Explanation:


Introduction / Context:
This problem tests understanding of string literals, pointer arithmetic, and how printf uses a format string. The code manipulates a pointer into the literal "%d\n" and then passes an adjusted pointer back to printf.


Given Data / Assumptions:

  • String literal: "%d\n" has bytes: '%' (index 0), 'd' (1), '\n' (2), '\0' (3).
  • str initially points to index 0.
  • str is incremented twice, so str points at index 2 (the newline).
  • printf receives str - 2, which points back to index 0.


Concept / Approach:
After two increments, str points at '\n'. Subtracting 2 moves the pointer back to '%'. Therefore, the format string passed to printf is effectively "%d\n". With the integer argument 300 supplied, printf prints the decimal representation followed by a newline.


Step-by-Step Solution:

Initialize str → "%d\n".Increment twice → str now points at '\n'.Compute str - 2 → pointer to '%' (start of format).printf("%d\n", 300) → prints 300.


Verification / Alternative check:
Replace the subtraction with a direct literal in printf and confirm identical output.


Why Other Options Are Wrong:

No output / Runtime error: The pointer ends up valid; it points to the beginning of the same literal.30 or 3: printf with "%d" prints the full integer value, not partial digits.


Common Pitfalls:
Forgetting the actual byte layout of the format string and miscounting pointer steps; assuming pointer math corrupts the pointer when it actually returns to a valid position within the same literal.


Final Answer:
300.

More Questions from Pointers

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion