Pointer-based string copy with printing at each step (assume enough destination space): what final string does str1 hold after the loop? #include<stdio.h> int main() { char str1[20] = "India"; // assume sufficient space to avoid overflow char str2[] = "CURIOUSTAB"; char *s1 = str1, *s2 = str2; while (*s1++ = *s2++) printf("%s", str1); printf(" "); return 0; } (We focus on the final content stored in str1 after copying completes.)

Difficulty: Medium

Correct Answer: CURIOUSTAB

Explanation:


Introduction / Context:
This classic pointer-copy loop uses the assignment expression inside the while condition to copy bytes from a source string to a destination and stops when the terminating null is copied. The example also prints the destination after each successful character copy. To avoid undefined behavior, we explicitly assume str1 has enough storage for the entire copy (for example, char str1[20] = "India").


Given Data / Assumptions:

  • str2 = "CURIOUSTAB\0" (length 10).
  • str1 has sufficient capacity (at least 11 bytes including the terminator).
  • Loop condition: while (*s1++ = *s2++) copies a byte, then tests the assignment value; it stops when the null byte (0) is copied.


Concept / Approach:
At each iteration, one character from str2 overwrites the next position in str1. Initially str1 contains "India"; after 10 character copies and the final null byte, str1 holds an exact copy of str2. The prints inside the loop show intermediate states, but the question asks for the final content of str1, which equals the source string.


Step-by-Step Solution:

Start: str1 = "India", str2 = "CURIOUSTAB".Copy C → str1 begins “Cndia…”.Copy progresses: after all characters, the former terminator in str1 is moved forward as the new characters extend the string.When the null from str2 is copied, the loop terminates; str1 is now “CURIOUSTAB”.


Verification / Alternative check:
Print str1 after the loop (outside the while). It shows “CURIOUSTAB”. The in-loop prints show transitional states but do not alter the final result.


Why Other Options Are Wrong:

India: This would be true only if no copying occurred.(null): printf of a null pointer, which we are not using here.Cndia: An intermediate state after copying only the first character, not the final state.The long mixed string: reflects misconceived concatenation of prints and is not the final stored value.


Common Pitfalls:
Forgetting to size the destination buffer to avoid overflow; misreading the assignment-in-condition idiom; confusing “console output during the loop” with the final string state in memory.


Final Answer:
CURIOUSTAB.

More Questions from Pointers

Discussion & Comments

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