Nested standard-library calls: what does this program print after strcat then strcpy? #include<stdio.h> #include<string.h> int main() { char str1[20] = "Hello", str2[20] = " World"; printf("%s ", strcpy(str2, strcat(str1, str2))); return 0; }

Difficulty: Medium

Correct Answer: Hello World

Explanation:


Introduction / Context:
This question tests understanding of strcat and strcpy return values and side effects, plus buffer sizing. The order of nested calls matters because each returns a pointer that becomes the input to the next function.



Given Data / Assumptions:

  • str1 has capacity 20 and initial contents "Hello".
  • str2 has capacity 20 and initial contents " World".
  • strcat(dest, src) appends src to dest and returns dest; strcpy(dest, src) copies src into dest and returns dest.


Concept / Approach:
Evaluate from inside: strcat(str1, str2) appends " World" to "Hello" producing "Hello World" in str1 and returns str1. Then strcpy(str2, returned_pointer) copies "Hello World" into str2 and returns str2. printf prints the resulting str2.



Step-by-Step Solution:
strcat(str1, str2) → str1 becomes "Hello World", function returns str1.strcpy(str2, ) → str2 becomes "Hello World".printf prints str2, so output is "Hello World".



Verification / Alternative check:
After execution, both str1 and str2 contain "Hello World". Buffers are sufficiently large, so there is no overflow.



Why Other Options Are Wrong:
"Hello" ignores the concatenation. "World" or "WorldHello" misunderstand the direction of copying and concatenation. Behavior is well-defined given buffer sizes.



Common Pitfalls:
Forgetting that strcat modifies the first argument; misremembering return values of these functions; insufficient buffer space can cause undefined behavior in other contexts.



Final Answer:
Hello World

More Questions from Strings

Discussion & Comments

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