Pointer arithmetic on string literals with printf: what is printed?
#include
int main()
{
printf(5 + 'Good Morning
');
return 0;
}
-
AGood Morning
-
BGood
-
CM
-
DMorning
-
Eorning
Answer
Correct Answer: Morning
Explanation
Introduction / Context:String literals are arrays of characters that decay to pointers when used in expressions. Adding an integer to such a pointer advances the pointer by that many characters. Passing the offset pointer to printf prints from that position onward.
Given Data / Assumptions:
- Literal is 'Good Morning'.
- Characters 0–4 are 'G o o d ␠' (space at index 4).
- 5 + literal points at the character 'M' of 'Morning'.
Concept / Approach:printf with a single pointer argument and no format specifiers treats the argument as a format string. Here the pointed-to substring is 'Morning'. It contains no % directives, so it prints as plain text starting at 'M'.
Step-by-Step Solution:
Base pointer → start of 'Good Morning'.Add 5 → pointer to 'M'.printf prints substring → 'Morning' → visually 'Morning' then newline.Verification / Alternative check:Change the offset to 0 to print the full phrase; change to 6 to print 'orning'.
Why Other Options Are Wrong:
'Good Morning' or 'Good': would require an offset of 0.'M': would require truncation to a single character.'orning': would be offset 6, not 5.Common Pitfalls:Forgetting that pointer addition steps by characters; misunderstanding that printf without format specifiers still prints the string when the data contains no % symbols.
Final Answer:Morning.