1. 程式人生 > 實用技巧 >C語言 實現一個記憶體拷貝函式

C語言 實現一個記憶體拷貝函式

#include <iostream>
#include <cstring>
using namespace std;


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; }