我正在经历一次!在C中的strcat函数。
我无法理解他们是如何使用递归和指针的。
下面是来自该源的代码片段。

char dest[100] = "I love";
char *src = "food";`

/* my_strcat(dest, src) copies data of src to dest. */
void my_strcat(char *dest, char *src)
{
  (*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest, src): 0 ;
}

最佳答案

把它撕成碎片:

(*dest) /* Is *dest different than '\0' ? */
   ? my_strcat(++dest, src) /* *dest is different than '\0', so increment dest pointer so it'll point to the next character and call my_strcat() again. Here we're searching for the end of the string dest. */

   : (*dest++ = *src++) /* *dest is equal to '\0', so we're at the end of *dest... We start to assign *src to *dest and increment both pointers to point to the next character. The lvalue of this assignment is also a comparison (is it different than '\0' ?). */

     ? my_strcat(dest, src) /* The previous comparison is different than '\0', so we'll call my_strcat() again (pointers have already been incremented and they now point to the next character) */

     : 0; /* The previous comparison is '\0', so we've reached the end of the src, so we're done. */

用if/else替换三元运算符:
/* Is *dest different than '\0' ? */
if (*dest != '\0') {
  /* *dest is different than '\0', so increment dest pointer so it'll point to the next character and call my_strcat() again. Here we're searching for the end of the string dest. */
  my_strcat(++dest, src);
} else {
  /* *dest is equal to '\0', so we're at the end of *dest... We start to assign *src to *dest and increment both pointers to point to the next character. The lvalue of this assignment is also a comparison (is it different than '\0' ?). */
  if ((*dest = *src) != '\0') {
    /* The previous comparison is different than '\0', so we'll call my_strcat() again (pointers have already been incremented and they now point to the next character) */
    my_strcat(++ dest, ++ src); /* Moved increments down for readability */
  } else {
     /* The previous comparison is '\0', so we've reached the end of the src, so we're done. */
    return;
  }
}

如果/else没有注释(可能更可读):
if (*dest != '\0') {
  my_strcat(++dest, src);
} else {
  if ((*dest = *src) != '\0') {
    my_strcat(++ dest, ++ src);
  } else {
    return;
  }
}

关于c - C中strcat函数的递归实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38318464/

10-17 00:31