C format strings, pointer arithmetic, and printf: what does this program print?
#include
int main()
{
char *str;
str = "%d
";
str++;
str++;
printf(str-2, 300);
return 0;
}
-
ANo output
-
B30
-
C3
-
D300
-
ERuntime error
Answer
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" and then passes an adjusted pointer back to printf.
Given Data / Assumptions:
- String literal: "%d" has bytes: '%' (index 0), 'd' (1), '' (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 ''. Subtracting 2 moves the pointer back to '%'. Therefore, the format string passed to printf is effectively "%d". With the integer argument 300 supplied, printf prints the decimal representation followed by a newline.
Step-by-Step Solution:
Initialize str → "%d".Increment twice → str now points at ''.Compute str - 2 → pointer to '%' (start of format).printf("%d", 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.