-3

I need help to concatenate strings using recursion in C.

I have 2 strings in input, src and dest, and I need to concatenate recursively src to dest, and store the concatenated string in dest.

e.g. if src="house" and dest="clock" , the output should be "chlooucske".

EDIT: This is my code:

char* str_concatenate(char dest[], char src[], int index){
    char temp[256]; // temporaty variable
    temp[index]=src[index]; //should copy each letter from src to temp
    temp[index+1]=dest[index]; //should copy each letter from dest to temp
    dest[index]=temp[index]; //should store the concatenated string into dest
    if (src[index]=='\0'){ //base case
        return dest;
    }
    else
        return str_concatenate(dest,src,index+1);
}

int main(){ //test
        char dest[]="house";
        char src[]="clock";

        char* ris=str_concatenate(dest,src,0);

        printf("dest= %s\n", ris); //should print "chlooucske" 
    return 0;
    }

However it copies the entire word from src to dest and prints it, it does not concatenate letters.

Ford1892
  • 741
  • 2
  • 9
  • 20
  • 2
    `dest` points to a string literal. String literals cannot be modified. Need to allocate a writable buffer. For example: `char dest[MAX_LEN] = "home";` – kaylum Apr 30 '16 at 11:19
  • 2
    How do you expect this function to *ever* return anything but a `NULL`-pointer? You know you can't pass `NULL` to `printf()`, right? – EOF Apr 30 '16 at 11:30
  • 1
    @marco2012, everyone seems to be annoyed with you today. They are voting you down and providing everything but constructive help. It looks like your code wants to interleave two strings? I don't see a concatenation happening. You have several issues. One is that you are allocating a new temp array each time your recursively enter your function. Another is that you return a null pointer in your base case, when you find a null terminator at src[index]. I suggest you tell us what your desired result is and other folks will help you get there. – nicomp Apr 30 '16 at 11:40
  • The usage of `malloc()` will give a big memory leak. Why not use normal arrays? – MikeCAT Apr 30 '16 at 11:43
  • I can help - use your debugger. – Martin James Apr 30 '16 at 12:10
  • @nicomp Thank you for your reply :) I understood my mistakes, and I'm trying to correct the code. If the strings are "home" and "clock", the concatenation would be "c h l o o m c e k" . – Ford1892 Apr 30 '16 at 13:05
  • @kaylum I forgot that char* can not be modified, thank you – Ford1892 Apr 30 '16 at 13:10

1 Answers1

2

The destination pointer is pointing to a string constant. You are trying to modify it and it causes your program to crash. You can use an array and initialize it as the destination string.

You may want to take a look at this. This explains your problem. What is the difference between char s[] and char *s?

Community
  • 1
  • 1
Yağmur Oymak
  • 467
  • 4
  • 13