思科C语言课程疑问:mystrcat函数中--destination的用法及逻辑解析
mystrcat函数的逻辑,尤其是--destination的用法 Let's walk through this handwritten mystrcat function step by step—this is a replica of the standard library's strcat function, which appends the source string to the end of the destination string and returns the starting address of the modified destination.
第一步:保存起始地址,找到destination的末尾
First, let's break down the first loop:
for(res = destination; *destination++; ) ;
res = destination: We store the original starting address ofdestinationinresright away. This is crucial because we're going to move thedestinationpointer around later, and we need to return the original start of the string when we're done.- The loop condition
*destination++works like this: we first read the character thatdestinationis pointing to, then increment thedestinationpointer by one. The loop keeps running as long as the character we read is not the null terminator\0(since\0evaluates to false in C). - Key detail: When this loop finishes,
destinationis pointing to the position after the\0of the originaldestinationstring—not the\0itself. That's exactly why we need the--destinationline next.
第二步:修正指针位置,完成字符串拼接
Now the second loop, where the --destination you're curious about comes into play:
for(--destination; (*destination++ = *source++); ) ;
--destination: This moves thedestinationpointer back one position, so it's now pointing directly at the original\0of thedestinationstring. This lets us overwrite that\0with the first character ofsource, which is how we start appending the new string.- The loop condition
(*destination++ = *source++)is a clever assignment trick:- We take the character that
sourceis pointing to - Assign it to the position
destinationis pointing to - Increment both
destinationandsourcepointers by one - The value of this entire expression is the character we just assigned. As long as that character isn't
\0, the loop continues. When we hit the\0at the end ofsource, the expression evaluates to false, and the loop stops—this conveniently copies the\0to the end of the new combined string, which is exactly what we need for a valid C string.
- We take the character that
最后:返回原始起始地址
return res; Since we saved the original start of destination in res at the beginning, returning it gives the caller the starting address of the fully concatenated string—just like the standard strcat does.
A quick example to make it concrete
Let's say destination points to "Hello" (memory layout: H e l l o \0) and source points to "World" (W o r l d \0):
- After the first loop,
destinationis pointing to the spot right after the\0of"Hello". --destinationmoves it back to the\0position.- The second loop copies
W,o,r,l,d, and finally\0intodestination's memory, one by one. - We return
res, which points to the start of the new string"HelloWorld".
内容的提问来源于stack exchange,提问作者Hiren Chafekar

