C语言 实现一个内存拷贝函数

#include<stdio.h>

void *Memory_Copy(void *to,const void *from,size_t length)//把b拷贝到a 拷贝sizeof(b)个 { char *from_p=(char *)from; char *to_p=(char *)to; if(from_p > to_p) { for(int i = 0;i < length; i++) { *to_p++=*from_p++; } } else{ from_p += length-1; to_p += length-1; for (int i = 0; i < length; i++) { *to_p--=*from_p--; } } return to_p; } int main() { char a[64]; char b[]="Today is the third of September"; char c[]={'a','b','c','d','e'}; int d[]={1,2,3}; int e[]={9,8}; memcpy(a,b,sizeof(b)); //输出 Today is the third of September printf("%s\n",a); Memory_Copy(a,c,sizeof(c)); //输出 abcde is the third of September printf("%s\n",a); Memory_Copy(d,e,sizeof(e)); cout<<d[0]<<d[1]<<d[2]<<endl; //输出 983 Memory_Copy(d,c,sizeof(c)); cout<<d[0]<<" "<<d[1]<<" "<<d[2]<<endl; //输出 1684234849 101 3 因为字节序是小端,d[0]存放d c b a 的ascii码 01100100 01100011 01100010 01100001 //d[1]存放e的ascii码且覆盖了0000 1000 d[2]没变化 return 0; }

 

posted @ 2020-09-14 17:32  归江渡鸟泅白浪  阅读(790)  评论(0)    收藏  举报