In C string-pointer assignment sequencing, what prints? #include<stdio.h> int main() { char t; /* unused */ char *p1 = "India", p2; p2 = p1; / p2 points to "India" / p1 = "CURIOUSTAB";/ p1 now points elsewhere */ printf("%s %s ", p1, p2); return 0; }

Difficulty: Easy

Correct Answer: CURIOUSTAB India

Explanation:


Introduction / Context:
This tests how pointer variables to string literals behave when reassigned. No characters are copied; only addresses move, so tracking which pointer refers to which literal is the key to predicting the printf output.



Given Data / Assumptions:

  • p1 initially points to the literal "India".
  • p2 is assigned p1, so p2 also points to "India".
  • p1 is then reassigned to point at "CURIOUSTAB".
  • Both literals are read-only program storage; we only print them.


Concept / Approach:
Pointer assignment changes what the pointer references; it does not duplicate strings. After p2 = p1, both point to "India". After p1 = "CURIOUSTAB", only p1 changes to the new literal; p2 still points to "India".



Step-by-Step Solution:
Initial: p1 → "India".p2 = p1 → p2 → "India".p1 = "CURIOUSTAB" → p1 → "CURIOUSTAB". p2 unchanged.printf prints: "CURIOUSTAB India".


Verification / Alternative check:
Add temporary prints after each assignment to observe addresses with %p, confirming p1 and p2 point to different literals at the end.



Why Other Options Are Wrong:
(a) and (c) would require copying data into p2 later, which did not happen. (d) would require p2 to be reassigned too. (e) The code is well-defined because we do not modify the literals.



Common Pitfalls:
Assuming assignment copies characters; thinking two pointers stay “linked” after one is reassigned; confusing literals with arrays.



Final Answer:
CURIOUSTAB India

More Questions from Strings

Discussion & Comments

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