When copying a string, I usually use the strcpy or strncpy function, and of course, the memcpy function can be implemented. So what's the difference between strcpy and memcpy?
Here is a piece of information I found (original address: http://www.cnblogs.com/stoneJin/archive/2011/09/16/2179248.html)
The difference between strcpy and memcpy
strcpy and memcpy are standard C library functions, and they have the following characteristics.
strcpy provides a copy of the string. That is, strcpy is used only for string copying, and it replicates not only the string contents, but also the terminator of the string.
The prototype of the known strcpy function is: char* strcpy (char* dest, const char* SRC);
MEMCPY provides replication of general memory. That is, memcpy has no limitations on what needs to be replicated and is therefore more widely used.
Char *strcpy (char * dest, const char * src)//implementation of SRC to dest copy
{
if (src = = NULL) | | (dest = = NULL)) Determine the validity of the parameter src and dest
{
return NULL;
}
Char *strdest = dest; Save the first address of the target string
while ((*strdest++ = *strsrc++)! = ');//Copy the contents of the SRC string to dest and
return strdest;
}
void *memcpy (void *memto,const void *memfrom,size_t size)
{
if (Memto = = NULL) | | (Memfrom = = NULL)) Memto and Memfrom must be valid
return NULL;
Char *tempfrom = (char *) memfrom; Save Memfrom First address
char *tempto = (char *) memto; Save Memto first address while
(Size--> 0) //Loop size times, copy memfrom value to memto
*tempto++ = *tempfrom++;
return memto;
}
strcpy and memcpy mainly have the following 3 aspects of the difference.
1, the content of the copy is different. strcpy can only copy strings, while memcpy copies arbitrary content, such as character arrays, integers, structs, classes, and so on.
2, the method of replication is different. strcpy does not need to specify a length, it encounters the string terminator of the copied character "\" before it ends, so it is prone to overflow. memcpy determines the length of the copy according to its 3rd parameter.
3, the use of different. It is common to use strcpy when copying strings and to replicate other types of data memcpy