Pointer arithmetic on string literals with printf: what is printed? #include<stdio.h> int main() { printf(5 + 'Good Morning '); return 0; }

Difficulty: Easy

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\n'.
  • 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\n'. It contains no % directives, so it prints as plain text starting at 'M'.


Step-by-Step Solution:

Base pointer → start of 'Good Morning\n'.Add 5 → pointer to 'M'.printf prints substring → 'Morning\n' → visually 'Morning' then newline.


Verification / Alternative check:
Change the offset to 0 to print the full phrase; change to 6 to print 'orning\n'.


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.

More Questions from Strings

Discussion & Comments

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