Search code examples
cstrcpy

Strcpy implementation in C


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?


Solution

  • Both copy the terminator, thus both are correct.

    Note that strcpy2() does the assignment (the copying) first, then the comparison. So it will copy the terminator before realizing it did, and stopping.

    Also, note that functions whose names start with str are reserved, so neither of these are actually valid as "user-level" code.