Strcpy and memcpy are both standard C library functions, which have the following features.
Strcpy provides string replication. That is, strcpy is only used for string copying. It not only copies the content of the string, but also copies the end character of the string.
It is known that the prototype of the strcpy function is char * strcpy (char * dest, const char * src );
Memcpy provides general memory replication. That is, memcpy has no restrictions on the content to be copied, so it is widely used.
Void * memcpy (void * dest, const void * src, size_t count );
Copy codeThe Code is as follows: char * strcpy (char * dest, const char * src) // implement the replication from src to dest.
{
If (src = NULL) | (dest = NULL) // judge the validity of the src and dest Parameters
{
Return NULL;
}
Char * strdest = dest; // Save the first address of the target string
While (* strDest ++ = * strSrc ++ )! = '\ 0'); // copy the contents of the src string to the dest
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 the first address of memFrom.
Char * tempTo = (char *) memTo; // Save the first address of memTo.
While (size --> 0) // loop size, copy the value of memFrom to memTo
* TempTo ++ = * tempFrom ++;
Return memTo;
}
Strcpy differs from memcpy in the following three aspects.
1. The copied content is different. Strcpy can only copy strings, while memcpy can copy any content, such as character arrays, integers, struct, and classes.
2. The replication method is different. Strcpy does not need to specify the length. It ends with the string Terminator "\ 0" of the copied character, so it is prone to overflow. Memcpy decides the copy Length Based on its 3rd parameters.
3. Different purposes. Strcpy is usually used to copy strings, while memcpy is generally used to copy data of other types.