Understand the difference between strcpy and memcpy

  • 2020-04-02 00:50:47
  • OfStack

Both strcpy and memcpy are standard C library functions with the following characteristics.
Strcpy provides a copy of a string. That is, strcpy is only used for string replication, and it copies not only the contents of the string, but also the end of the string.
Known strcpy function prototype is: char* strcpy(char* dest, const char* SRC);
Memcpy provides replication of general memory. Memcpy has no restrictions on what needs to be copied, so it is more widely used.
Void *memcpy(void *dest, const void * SRC, size_t count);

char * strcpy(char * dest, const char * src) //Implement the copy of SRC to dest
{ 
  if ((src == NULL) || (dest == NULL)) //Determine the validity of parameters SRC and dest
  { 

      return NULL; 
  } 
  char *strdest = dest;        //Saves the first address of the target string
  while ((*strDest++ = *strSrc++)!='0'); //Copy the contents of the SRC string under 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 memFrom address
  char *tempTo = (char *)memTo;                  //Save the first address of memTo & NBSP; & have spent & have spent & have spent & have spent & have spent
  while(size -- > 0)                //Loop the size times, copying the value of memFrom into memTo
         *tempTo++ = *tempFrom++ ;   
  return memTo; 
} 

There are three main differences between strcpy and memcpy.
1. Different contents are copied. Strcpy can only copy strings, while memcpy can copy anything, such as character arrays, integers, structs, classes, and so on.
2. Different methods of replication. Strcpy does not need to specify a length; it only ends when it encounters the string terminator "\0" for the copied character, so it is prone to overflow. The memcpy determines the length of replication based on its third parameter.
3. Different USES. Strcpy is typically used when copying strings, and memcpy when copying other types of data

Related articles: