[英]C strcpy copies string and adds another character
我被分配使用我的名字演示我自己制作的strcpy函數。 我正在使用CodeBlocks,我遇到的問題是,對於我輸入的一些隨機字符組合,它大部分時間都會復制並打印相同的字符。 但是,如果我輸入我的名字Mark,則打印的語句將顯示string1 = Mark (我的輸入),而對於string2,它將打印utring2 =MarkH▀ 。 直到現在我還沒有意識到打印utring2而不是string2,所以現在我也想知道它。
#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▀
當測試s2[i] != '\\0'
失敗時,你沒有進入循環,這意味着你忽略了字符串終結符'\\0'
。
因此,您需要在循環后執行s1[i]='\\0'
以確保字符串s1
的終止。 然后你可以返回你復制的字符串。
你也需要復制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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.