简体   繁体   中英

C strcpy copies string and adds another character

I was assigned to demonstrate my own made strcpy function using my name. 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. 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▀ . I hadn't realized it was printing utring2 instead of string2 until now, so now I'm wondering about that too.

#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' .

So you need to do s1[i]='\\0' after the cycle to ensure the termination of string s1 . And then you could return your copied string.

you need to copy the 0 too, do s1[i] = 0 before returning.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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