Are there any cases where strcpy
can't be replaced by strcat
(after setting the initial character of the target to '\0'
)? I don't think so.
Does that mean you should always use strcat
when strcpy
would do the job? Absolutely not.
strcpy
makes no assumptions about the initial contents of the target array.
strcat
requires the target to contain a terminating '\0'
null character -- and if it's not in the initial position, it will scan for it, to and possibly beyond the end of the array.
It's true that
strcpy(dest, source);
is equivalent to
dest[0] = '\0';
strcat(dest, source);
so you can always use strcat
instead of strcpy
. That doesn't mean you should.
strcpy
is commonly used to replace the contents of an array:
char s[100] = "hello, world";
...
strcpy(s, "goodbye, cruel world");
Replacing that last line with:
s[0] = '\0';
strcat(s, "goodbye, cruel world");
would just make the code more verbose and more difficult to read.
If you want to copy a string into an array, use strcpy
. If you want to concatenate a string onto an existing one, use strcat
.