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

时间:2013-02-05 13:18:57

标签: c

关于如何编写获得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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您的复制逻辑非常完美。只是你没有返回任何价值(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;
}
相关问题