memcpy 的内存拷贝函数

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 void *memory(void *dst,const void *src,size_t s)
 6 {
 7 
 8    const char* psrc=static_cast<const char*>(src);
 9     char* pdst=static_cast<char*>(dst);
10 
11     if(psrc==NULL||pdst==NULL)
12         return NULL;
13 
14     if(pdst>psrc&&pdst<(psrc+s))
15     {
16         for(size_t i=s-1;i!=-1;i--)
17             pdst[i]=psrc[i];
18     }
19     else
20     {
21         for(size_t i=0;i<s;++i)
22             pdst[i]=psrc[i];
23     }
24     return dst;
25 }
26 int main()
27 {
28    char buf[100]="abcdefghijk";
29    cout << buf << endl;
30    memory(buf+2,buf,5);
31    cout << buf;
32    return 0;
33 }

 函数memcpy是实现,主要是对函数memcpy的理解透彻,防止内存自己拷贝自己,存在从前向后拷贝和从后向前拷贝的顺序。

posted @ 2018-08-23 17:26  Scott9527  阅读(1790)  评论(0编辑  收藏  举报