Copying a C string using pointer assignment in the while condition and again in the body: what final string is printed? #include<stdio.h> int main() { char str1[] = 'Hello'; char str2[10]; char *t, *s; s = str1; t = str2; while (*t = *s) *t++ = *s++; printf('%s ', str2); return 0; }

Difficulty: Medium

Correct Answer: Hello

Explanation:


Introduction / Context:
This code demonstrates a common pointer-copy idiom with a twist: it both assigns in the while condition and repeats an assignment in the loop body with post-increments. Despite seeming redundant, the resulting contents of str2 after the loop are important to determine correctly.


Given Data / Assumptions:

  • str1 = 'Hello\0'.
  • str2 has enough space (10 bytes).
  • While condition: while (*t = *s) copies the current byte, then tests it for nonzero.
  • Body: *t++ = *s++ copies the next byte and advances both pointers.


Concept / Approach:
On each iteration, the condition copies the 'current' byte; the body then copies the 'next' byte and advances. When the null terminator is encountered by the condition assignment, the loop exits and the string in str2 is correctly terminated. Despite copying certain bytes twice, the final effect is a normal copy of 'Hello' into str2.


Step-by-Step Solution:

Iteration 1: condition copies 'H', body copies 'e' and advances.Iteration 2: condition sets 'e' again (same value), body copies 'l'.… continues until the null byte is assigned by the condition → exit.Result: str2 holds 'Hello' (properly null-terminated).


Verification / Alternative check:
Printing str2 shows 'Hello'. Rewriting the loop in the canonical form while ((*t++ = *s++) != '\0'); produces the same final string.


Why Other Options Are Wrong:

'HelloHello': would require concatenation or two full copies.'No output': the program prints at least a newline with content.'ello': would require starting from the second character.


Common Pitfalls:
Confusing the immediate console output with the final memory content; assuming the double assignment corrupts the copy (it does not here).


Final Answer:
Hello.

More Questions from Strings

Discussion & Comments

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