模拟实现内存拷贝函数my_memcpy

时间:2022-08-04 00:58:37

可以实现重叠拷贝(等价于memmove函数的实现)

#include<stdio.h>
#include<assert.h>

void* my_memcpy(void* arr1,const void* arr2, size_t num) {
void* ret = arr1;
assert(arr1);
assert(arr2);
if (arr1>=arr2) {//为了实现重叠拷贝
while (num--) {
*((char*)arr1 + num) = *((char*)arr2 + num);
}
//*(char*)arr1 = *(char*)arr2;
}
else {
while (num--) {
*(char*)arr1 = *(char*)arr2;
++(char*)arr1; //强制类型转换低于++的优先级
++(char*)arr2;
}
}
return ret;
}
int main() {
int arr1[8] = { 1,2,3,4,5,6,7,8 };
int arr2[20] = {0};
//模拟实现内存拷贝函数my_memcpy
int* ret = my_memcpy(arr1+2, arr1, 20);
int i = 0;
for (i = 0; i < 8; i++) {
printf("%d ", arr1[i]);
}
return 0;
}