简体   繁体   English

C strcpy复制字符串并添加另一个字符

[英]C strcpy copies string and adds another character

I was assigned to demonstrate my own made strcpy function using my name. 我被分配使用我的名字演示我自己制作的strcpy函数。 I'm using CodeBlocks, and the problem I'm having is that for some random combinations of characters I input, it will most of the time copy and print the same characters. 我正在使用CodeBlocks,我遇到的问题是,对于我输入的一些随机字符组合,它大部分时间都会复制并打印相同的字符。 However, if for example I input my name, Mark,the printed statement will show string1 = Mark (my input) and for string2 it'll print utring2 = MarkH▀ . 但是,如果我输入我的名字Mark,则打印的语句将显示string1 = Mark (我的输入),而对于string2,它将打印utring2 =MarkH▀ I hadn't realized it was printing utring2 instead of string2 until now, so now I'm wondering about that too. 直到现在我还没有意识到打印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;
}

My complete output is as follows: 我的完整输出如下:

Mark
string1 = Mark
utring2 = MarkH▀

When the test s2[i] != '\\0' fails you're not entering the cycle, that means that you ignore the string terminator '\\0' . 当测试s2[i] != '\\0'失败时,你没有进入循环,这意味着你忽略了字符串终结符'\\0'

So you need to do s1[i]='\\0' after the cycle to ensure the termination of string s1 . 因此,您需要在循环后执行s1[i]='\\0'以确保字符串s1的终止。 And then you could return your copied string. 然后你可以返回你复制的字符串。

you need to copy the 0 too, do s1[i] = 0 before returning. 你也需要复制0,在返回之前做s1[i] = 0

or do it 或者这样做

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM