Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strcpy implementation in C

Tags:

c

strcpy

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?

like image 824
Hommer Smith Avatar asked Jan 23 '13 09:01

Hommer Smith


1 Answers

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)));
like image 76
herohuyongtao Avatar answered Sep 30 '22 04:09

herohuyongtao