内存拷贝实现

来源:互联网 发布:linux下卸载jdk 编辑:程序博客网 时间:2024/05/03 14:28
问题描述:写一个函数,完成内存之间的拷贝

  1. #include<iostream>
  2. using namespace std;
  3. // 返回void *,可支持链式操作 
  4. void  *memcpy_(void *dest, const void *source, unsigned int c_length)
  5. {
  6.      assert(dest && source);
  7.      if(dest==source)return dest;
  8.      char *p1=static_cast<char*>(dest);
  9.      const char *p2=static_cast<const char*>(source);
  10.      if(p1>p2 && p1<p2+c_length)
  11.      {
  12.           //存在内存重叠区域 
  13.           for(int i=c_length-1; i>=0; i--)
  14.           p1[i]=p2[i];
  15.      }
  16.      else 
  17.      {
  18.           for(int i=0; i<c_length; i++)
  19.               p1[i]=p2[i];
  20.      }  
  21.      return dest;
  22. }
  23. int main()
  24. {
  25.     char source[]="Hello, My name is shark/n";
  26.     cout<<strlen(source)<<endl;
  27.     char dest[30];
  28.     memcpy_(&dest, &source, strlen(source));
  29.     cout<<dest<<endl;
  30.     getchar();  
  31.     return 0;
  32. }