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

标签 c

我被指派用我的名字演示我自己制作的 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的终止。然后你可以返回你复制的字符串。

关于C strcpy 复制字符串并添加另一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445923/

相关文章:

c - 抑制特定的氧气警告

实时控制音量

c - 忽略返回值(C 编程)

c - 返回数组中的值并打印它

c - C中的双指针疑惑

javascript - WASM 可以用来检查 JS 方法的完整性吗?

c - 如何以整数而不是 ASCII 代码值获取输出

c - MPI - 工作/池示例

c - 将因子数量存储为 C 中的变量

c - SPI 闪存编程问题