1.memcpy
#include <stdio.h> #include<assert.h> void* my_memcpy(void* dest, const void* scr, size_t count) { assert(dest && scr); void* ret = dest; while (count--) { *(char*)dest = *(char*)scr; //一个字节一个字节转移 强转成char* dest = (char*)dest + 1; //强制类型转换不是永久性动作 所以要在强转+1 scr = (char*)scr + 1; } return ret; //返回目标地址起始位置 void*的指针 } int main() { int arr1[] = { 1,2,3,4,5,6,7,8,9,10 }; int arr2[5] = { 0 }; my_memcpy(arr2, arr1, 20); return 0; }
2.memmove(实现了自我交叉拷贝)
void* my_memmove(void* dest, const void* scr, size_t count) { assert(dest&& scr); void* ret = dest; if (dest < scr) //dest<scr时 从前往后copy 与memcpy一样 { while (count--) { *(char*)dest = *(char*)scr; dest = (char*)dest + 1; scr = (char*)scr + 1; } } else //当dest>=scr时从后往前 { while (count--) { *((char*)dest + count) = *((char*)scr + count); } } return ret; } int main() { int arr1[] = { 1,2,3,4,5,6,7,8,9,10 }; my_memmove(arr1+2, arr1, 20); return 0; }