Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
Hi, guys trying to implement own strcpy function, but no output is being printed. Please help.

Objective-C
#include<stdio.h>
#include<string.h>

void strcpy_own(char dest[], char src[], int len);

int main()
{
    char src[15]="jeevan", dest[15];
    int length=0;
    length = strlen(src)+1;
    strcpy_own(dest,src,length);
    return 0;
}

void strcpy_own(char dest[], char src[], int len)
{
    int i=0;
    for(i=0;i<len;i++)
    {
        while(src[i]!='\0')
        dest[i]=src[i];

    }
    dest[strlen(dest)+1]='\0';
            printf("%s",dest);
            getchar();
}
Posted
Updated 19-Aug-14 21:23pm
v3
Comments
Sergey Alexandrovich Kryukov 20-Aug-14 3:57am    
Such functions should not print anything. The calling code can print it...
—SA
Jeevan83 24-Aug-14 14:09pm    
Gotcha!

Your inner while-loop does not increment i,
C#
for(i=0;i<len;i++)
{
    while(src[i]!='\0')
       dest[i]=src[i]; // i does not get updated here, the while will never exit

}


Change it to something like this;
C#
for(i=0;i<len;i++)
{
    dest[i]=src[i];
    if (src[i] =='\0')
        break;
}

Remember that you want to copy the last '\0' from src to dest or dest won't be properly zero-terminated.

Hope this helps,
Fredrik
 
Share this answer
 
I'm not surprised.
If the first character in the source string isn't a null, this loop will never exit:
C#
while(src[i]!='\0')
dest[i]=src[i];

Try this:
C#
for(i=0;i<len;i++)
{
    dest[i]=src[i];
    if (src[i]=='\0') break;
}
And be careful with the line after the loop - if the source string is full then you could overrun the output array.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900