Search code examples
cstringpointersstrcpy

How to properly implement strcpy in c?


According to this: strcpy vs strdup, strcpy could be implemented with a loop, they used this while(*ptr2++ = *ptr1++). I have tried to do similar:

#include <stdio.h>
#include <stdlib.h>
int main(){
    char *des = malloc(10);
    for(char *src="abcdef\0";(*des++ = *src++););
    printf("%s\n",des);
}

But that prints nothing, and no error. What went wrong?

Thanks a lot for answers, I have played a bit, and decided how best to design the loop to see how the copying is proceeding byte by byte. This seems the best:

#include <stdio.h>
#include <stdlib.h>

int main(){
    char *des = malloc(7);
    for(char *src="abcdef", *p=des; (*p++=*src++); printf("%s\n",des));
}

Solution

  • In this loop

    for(char *src="abcdef\0";(*des++ = *src++););
    

    the destination pointer des is being changed. So after the loop it does not point to the beginning of the copied string.

    Pay attention to that the explicit terminating zero character '\0' is redundant in the string literal.

    The loop can look the following way

    for ( char *src = "abcdef", *p = des; (*p++ = *src++););
    

    And then after the loop

    puts( des );
    

    and

    free( des );
    

    You could write a separate function similar to strcpy the following way

    char * my_strcpy( char *des, const char *src )
    {
        for ( char *p = des; ( *p++ = *src++ ); );
    
        return des;
    }
    

    And call it like

    puts( my_strcpy( des, "abcdef" ) )'
    free( des );