C strcpy copies a string and appends another character

I was assigned to demonstrate my own strcpy function using my name. I'm using CodeBlocks and the problem I'm running into is that for some random combinations of characters that I enter, it will copy and print the same characters most of the time. However, if, for example, I enter my name, Mark, the print statement will show string1 = Mark (my input), and for line2 it will print utring2 = MarkHβ–€ . I didn't realize that it was printing utring2 instead of string2 so far, 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 looks like this:

Mark
string1 = Mark
utring2 = MarkHβ–€

      

+3


source to share


2 answers


When the test s2[i] != '\0'

fails, you do not enter the loop, which means that you are ignoring the line terminator '\0'

.



So, after the loop, you need to execute s1[i]='\0'

to ensure line completion s1

. And then you can get your copied string back.

+3


source


you need to also copy 0, before s1[i] = 0

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;

      

+2


source







All Articles