2016-04-30 91 views
-3

我需要幫助來連接使用遞歸字符串C.連接字符串遞歸用C

我在輸入兩個字符串,SRCDEST,我需要連接遞歸SRCdest,並將連接字符串存儲在dest中。

例如如果src="house"dest="clock",則輸出應爲"chlooucske"

編輯:這是我的代碼:

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

但是它直接複製整個單詞SRCDEST並打印出來,它不會串連字母。

+2

'dest'指向一個字符串文字。字符串文字不能修改。需要分配一個可寫緩衝區。例如:'char dest [MAX_LEN] =「home」;' – kaylum

+2

您如何期待此函數*返回除NULL指針外的任何內容?你知道你不能將'NULL'傳遞給'printf()',對吧? – EOF

+1

@ marco2012,今天大家似乎都很生氣。他們投票給你,並提供一切,但建設性的幫助。它看起來像你的代碼想交錯兩個字符串?我沒有看到連接發生。你有幾個問題。一種是每次遞歸輸入函數時都要分配一個新的臨時數組。另一個是當你在src [index]處找到一個空終止符時,你在你的基本情況下返回一個空指針。我建議你告訴我們你想要的結果是什麼,其他人會幫助你到達那裏。 – nicomp

回答