c如何编写将字符串复制到某个位置的递归函数



关于如何编写获得 2 个参数的递归函数的任何想法:第一个是地址 D(字符的位置(。第二个是字符串。该函数将字符串 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((;d oesn't work –

输出应该是 klomopqrstuvwqyz

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

你的复制逻辑是完美的。只是您没有返回任何值 (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("%sn%sn",t,dest); //t==dest. thus you don't really have to return anything from the function.
    return 0;
}

最新更新