Strcpy implementation in C

Hommer Smith picture Hommer Smith · Jan 23, 2013 · Viewed 42.6k times · Source

So, I have seen this strcpy implementation in C:

void strcpy1(char dest[], const char source[])
{
    int i = 0;
    while (1)
    {
        dest[i] = source[i];

        if (dest[i] == '\0')
        {
            break;
        }

        i++;
    } 
}

Which to me, it even copies the \0 from source to destination.

And I have also seen this version:

// Move the assignment into the test
void strcpy2(char dest[], const char source[]) 
{
    int i = 0;
    while ((dest[i] = source[i]) != '\0')
    {
        i++;
    } 
}

Which to me, it will break when trying to assign \0 from source to dest.

What would be the correct option, copying \0 or not?

Answer

herohuyongtao picture herohuyongtao · Nov 25, 2013

The code should look like as follows:

char * strcpy(char *strDest, const char *strSrc)
{
    assert(strDest!=NULL && strSrc!=NULL);
    char *temp = strDest;
    while(*strDest++ = *strSrc++); // or while((*strDest++=*strSrc++) != '\0');
    return temp;
}

You can NOT delete the second line char *temp = strDest; and directly return strDest. This will cause error for the returned content. For example, it will not return correct value (should be 22) will checking the length of returned char *.

char src_str[] = "C programming language";
char dst_str[100];
printf("dst_str: %d\n", strlen(strcpy(dst_str, src_str)));