cstrcpy

Correct way to use strcpy() function?


What is the correct way to use strcpy() function? I have done it in two ways, and both times the program worked just fine, so I was wondering what's "more correct" way to use it. I want to copy string s2 to s1.

This one:

s1=strcpy(s1, s2);  

or to just write:

strcpy(s1, s2);

Solution

  • The second way is correct. The return value of strcpy() is always the same as its first argument, so your first version is equivalent to:

    strcpy(s1, s2);
    s1 = s1;
    

    That second assignment is obviously pointless. And it would be invalid if s1 were an array rather than a pointer variable, since you can't assign to arrays.