Understand the difference between memmove of and memcpy of and how to implement it

  • 2020-04-02 01:06:25
  • OfStack

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/201305291648323.gif ">
The code is as follows:

//Memmove.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;


void* memmove(void* dest, const void* src, size_t n)
{
 if (n <= 0)
 {
  cout << "Invalid count number." << endl;
 }
 if (dest == NULL || src == NULL)
 {
  cout << "The dest or src address is null." << endl;
 }
 if (dest == src)
 {
  cout << "The dest equals src." << endl;
 }
 if ((char*)dest <= (char*)src || (char*)dest >= (char*)src + n)
 {//Corresponding to the three cases of 2,3 and 4 in the figure, unused items in SRC will not be overwritten during the assignment process
  char* de = (char*)dest;
  const char* sr = (const char*)src;
  while (n--)
  {
   *de++ = *sr++;
  }
 }
 else
 {//The first case in the graph
  char* de = (char*)dest + n -1;
  const char* sr = (const char*)src + n - 1;
  while (n--)
  {
   *de-- = *sr--;
  }
 }
 return dest;
}


void* memmcpy(void* dest, const void* src, size_t n)  
{  
  if (n <= 0)  
{  
  cout << "Invalid count number." << endl;  
}  
 if (dest == NULL || src == NULL)  
 {  
     cout << "The dest or src address is null." << endl;  
 }  
 if (dest == src)  
 {  
   cout << "The dest equals src." << endl;  
 }  
 char* de = (char*)dest;  
 const char* sr = (const char*)src;  
 while (n--)  
 {  
   *de++ = *sr++;  
 }  
  return dest;  
}  


int _tmain(int argc, _TCHAR* argv[])
{
 char* p = "hello,world";  
 char dest[12] = {0};
 char *q = (char*)memmove(dest,p,5); 
 cout << dest << endl;    
 cout << q << endl;  
 return 0;   
}


Related articles: