2014-10-19 132 views
3

我被分配用我的名字來演示自己創建的strcpy函數。我使用的是CodeBlocks,我遇到的問題是對於我輸入的一些隨機組合字符,它會在大部分時間複製和打印相同的字符。但是,例如,如果我輸入了我的名字Mark,則打印的語句將顯示string1 =標記(我的輸入),對於string2它將打印utring2 =MarkH▀。直到現在,我還沒有意識到它正在打印utring2而不是string2,所以現在我也在想這個。C strcpy複製字符串並添加另一個字符

#include <stdio.h> 
char* mystrcpy(char* s1, char* s2); 

main() 
{ 
    char string1[100], string2[100]; //declaring two strings with buffer sizes of 100 
    gets(string1);     //takes input from user for string1 
    mystrcpy(string2, string1);  //calls string copy function 
    printf("string1 = "); 
    puts(string1);   //prints string1 
    printf("string2 = "); 
    puts(string2);   //prints new string2 which should be the same as string1 
    return 0;   //ends main program 
} 

char* mystrcpy(char* s1, char* s2) 
{ 
    int i=0; //initializes element counter at 0 for first element 
    while(s2[i] != '\0') //loops until null is reached 
    { 
     s1[i] = s2[i];  //copies the i-th element of string1 to the corresponding element of string2 
     i++;   //increments element counter 
    } 
    return s1; 
} 

我的完整輸出如下:

Mark 
string1 = Mark 
utring2 = MarkH▀ 

回答

3

當測試s2[i] != '\0'失敗,你不進入循環,這意味着你忽略字符串結束'\0'

所以你需要做s1[i]='\0'之後的週期來確保字符串s1的終止。然後你可以返回你複製的字符串。

+1

啊這個解釋說清楚了。沒有意識到我也必須複製它。第一次用字符串。萬分感謝。 – 2014-10-19 00:36:51

2

您需要將0複製過,在返回前做s1[i] = 0

或做

int i=0; //initializes element counter at 0 for first element 
    do 
    { 
     s1[i] = s2[i];  //copies the i-th element of string1 to the corresponding element of string2 
     i++;   //increments element counter 
    } while(s2[i] != '\0') //loops until null is reached 
    return s1; 
相關問題