Difficulty: Easy
Correct Answer: 2
Explanation:
Introduction / Context:
The routine scans a C-string and copies into tmp
each character that immediately follows a space in str
. It then returns the length of tmp
. This tests pointer arithmetic and pre/post-increment order in a loop.
Given Data / Assumptions:
i
before reading the next character.
Concept / Approach:
We need each character after a space. In the sample text there are two spaces: between “Welcome” and “to”, and between “to” and “CuriousTab.com!”. Therefore, the characters copied are the first letters of the following words, namely 't'
and 'C'
.
Step-by-Step Solution:
1) Initialize i=0
, j=0
. 2) Traverse until null terminator. 3) When str[i]
equals space, post-increment makes i
point to the next character; that character is assigned to tmp[j++]
. 4) For the two spaces, copied characters are 't'
and 'C'
, so tmp
becomes “tC”. 5) strlen(tmp)
is 2, which is printed.
Verification / Alternative check:
Add another space in the source string; the count increases accordingly, confirming the algorithm.
Why Other Options Are Wrong:
1 undercounts spaces; 24/25 misinterpret the function as returning the whole string length; 0 would require no spaces or an empty string.
Common Pitfalls:
Misunderstanding post-increment usage; off-by-one when reading the character after the space; forgetting to null-terminate tmp
.
Final Answer:
2
Discussion & Comments