0

any ideas about how to write a RECURSIVE function that gets 2 parameters : first is an address d (a location of char). second is a string. The function copies the string s to a location starting at d. The function returns d as a result ! can we do it without strcpy ?

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

where is the mistake ? (found ) put still there is a problem ! what if the location d overlaps some location that is already occupied by s ?
this for example strcpy(p1, "abcdefghijklomopqrstuvwqyz"); printf(copy_r(p1, p1+10));doesnt work –

output should be klomopqrstuvwqyz

user2042145
  • 141
  • 1
  • 1
  • 9

2 Answers2

1

where is the mistake

Well, there isn't any mistake, this code sample works correctly... the only issue I see is that it doesn't work exactly as you expect. You mentioned you wanted it to The function returns d as a result and you don't have it doing that.

The code currently takes s and copies the contents into d so if you had something like:

char * str = "hello";
char * ptr = malloc(6);
copy_r(str, ptr);
// now ptr has "hello" too
Mike
  • 47,263
  • 29
  • 113
  • 177
1

Your copy logic is perfect. Just that you are not returning any value (d)...

This should work:

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;
}

sample usage:

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;
}
anishsane
  • 20,270
  • 5
  • 40
  • 73