【问题标题】:How to write recursive function that copies a string to a location?如何编写将字符串复制到某个位置的递归函数?
【发布时间】:2025-11-24 05:20:04
【问题描述】:

关于如何编写获取 2 个参数的 RECURSIVE 函数的任何想法: 首先是地址 d(char 的位置)。 第二个是字符串。 该函数将字符串 s 复制到从 d 开始的位置。 该函数返回 d 作为结果! 我们可以在没有 strcpy 的情况下做到吗?

    copy_r(char *s, char *d)
{
    *d = *s;
    if(*s)return copy_r(++s, ++d);
}

错在哪里? (成立 ) 还是有问题!如果位置 d 与某个已被 s 占用的位置重叠怎么办?
例如这个 strcpy(p1,“abcdefghijklomopqrstuvwqyz”); printf(copy_r(p1, p1+10));不起作用 –

输出应该是 klomopqrstuvwqyz

【问题讨论】:

  • 是的,不用strcpy也可以,递归也可以。
  • 这和问“strcpy()可以用C实现吗?”一样,答案当然是肯定的。
  • 当然可以……试过什么了吗?
  • 作业问题?是的,你尝试过什么
  • 任何想法如何递归地编写它?提示可能

标签: c


【解决方案1】:

where is the mistake

嗯,没有任何错误,此代码示例可以正常工作...我看到的唯一问题是它不能完全按照您的预期工作。你提到你想要它到The function returns d as a result,但你没有这样做。

代码当前采用s 并将内容复制到d 所以如果你有类似的东西:

char * str = "hello";
char * ptr = malloc(6);
copy_r(str, ptr);
// now ptr has "hello" too

【讨论】:

  • 将添加一个停止条件,如 if(s=='\0') return d;它会工作吗?
【解决方案2】:

你的复制逻辑是完美的。只是你没有返回任何值(d)......

这应该可行:

char* copy_r(char *s, char *d)
{
    *d = *s;
    if(*s)
      return copy_r(s + 1, d + 1 ) - 1 ; //-1 is to take care of d+1 part
    else
      return d;
}

示例用法:

int main(){
    char src[]="hello world";
    char dest[50];

    char* t=copy_r(src,dest);

    printf("%s\n%s\n",t,dest); //t==dest. thus you don't really have to return anything from the function.
    return 0;
}

【讨论】:

  • 谢谢!还是有问题!如果位置 d 与某个已被 s 占用的位置重叠怎么办?
  • strcpy(p1, "abcdefghijklomopqrstuvwqyz"); printf(copy_r(p1, p1+10));这例如不起作用
  • 那么对于这个例子,预期的输出是什么?
  • 输出是 klomopqrstuvwqyz
  • & 你为什么认为期望klomopqrstuvwqyz 是正确的(阅读:适当/正确)?这没有源副本...
最近更新 更多