首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C strcpy复制字符串并添加另一个字符。

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

Stack Overflow用户
提问于 2014-10-19 00:17:59
回答 2查看 358关注 0票数 3

我被指派使用我的名字来演示我自己创建的strcpy函数。我使用的是CodeBlocks,我遇到的问题是,对于我输入的一些随机字符组合,它大部分时间都会复制和打印相同的字符。但是,例如,如果我输入我的名字,则打印的语句将显示string1 = Mark (我的输入),对于string2,它将打印utring2 = MarkH▀。直到现在我才意识到它是在打印utring2而不是string2,所以现在我也在想这个问题。

代码语言:javascript
运行
复制
#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;
}

我的全部产出如下:

代码语言:javascript
运行
复制
Mark
string1 = Mark
utring2 = MarkH▀
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-19 00:29:58

当测试s2[i] != '\0'失败时,您没有进入循环,这意味着您忽略了字符串终止符'\0'

因此,您需要在循环之后执行s1[i]='\0',以确保字符串s1的终止。然后你可以返回你复制的字符串。

票数 3
EN

Stack Overflow用户

发布于 2014-10-19 00:19:55

您也需要复制0,在返回之前执行s1[i] = 0

或者去做

代码语言:javascript
运行
复制
    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;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26445923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档