In C, pointer arithmetic on a format string: what does this print? #include<stdio.h> int main() { char *p; p = "%d "; p++; p++; printf(p - 2, 23); return 0; }

Difficulty: Easy

Correct Answer: 23

Explanation:


Introduction / Context:
This question checks your understanding of pointer arithmetic with string literals and how printf uses a format-string pointer. Although the code moves the pointer forward and then back, it ultimately passes a valid format string to printf.



Given Data / Assumptions:

  • p points to the literal "%d\n". In memory this is the byte sequence '%', 'd', '\n', '\0'.
  • p++ twice advances p to point at '\n'.
  • printf expects a format string as its first argument.


Concept / Approach:
Pointer arithmetic is reversible. After two increments, p points at the newline byte. Subtracting 2 returns to the original base address where the '%' character resides. Passing p - 2 to printf therefore provides a valid "%d\n" format string, and 23 is the integer argument to format and print.



Step-by-Step Solution:
Initial: p → '%' of "%d\n".After p++ twice: p → '\n'.Compute p - 2: pointer again points to '%'.printf(p - 2, 23) is equivalent to printf("%d\n", 23).Therefore the program prints 23 followed by a newline.



Verification / Alternative check:
Replace printf(p - 2, 23) with printf("%d\n", 23) to confirm identical behavior. Running the original code prints 23 because the pointer arithmetic returns to the correct start of the format.



Why Other Options Are Wrong:
21 assumes arithmetic on the number, not on the pointer. “Error” or “No output” would occur only if an invalid pointer were passed, which does not happen here. It is not undefined behavior because the resulting pointer still points within the same array object (the literal), which is permitted.



Common Pitfalls:
Assuming that advanced pointer gymnastics are inherently invalid; forgetting that format strings are just char arrays and pointer math can legally traverse them.



Final Answer:
23

Discussion & Comments

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