0

I'm trying to reproduce the behaviour of strcpy in c, my problem is that the function works but it append extra stuff at the end.

char    *ft_strcpy(char * dst, const char * src)
{
int i;
i = 0;
while (src[i] != '\0') {
    dst[i] = src[i];
    i++;
}
return dst;
}

When i run it I get the following.

int main()
{
char p[] = {};
char z[] = "Hello World";
ft_strcpy(p,z);
printf("%s\n", p);
return 0;
}

function results

2 Answers2

2

You aren't copying the nul terminator so the printf doesn't know to stop.

Just add dst[i] = 0; after the loop.

Also, you haven't allocated any space for p, so you're going to get undefined behavior. For a first test just do something like char p[100]; and make sure z is never > 99 chars long. Eventually you need a better fix, but that will get you started.

John3136
  • 28,809
  • 4
  • 51
  • 69
0

TenTen,

Set dest[i] to '\0' after ending the loop. Here is the code:

int main()
    {
    char src[100], dest[100], i;
    printf("Enter string Src: ");
    scanf("%s",src);
    for(i=0; src[i]!='\0'; ++i)
        {
        dest[i]=src[i];
        }
    dest[i]='\0';
    printf("String Dest: %s",dest);
    return 0;
    }
Vishwas R
  • 3,340
  • 1
  • 16
  • 37