#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
//memmove 和 memcpy 的区别在于 遇到内存重叠的问题时 memcpy无法正确拷贝
//这时就用到memmove 解决
void* Memmove(void* dest, void* src, size_t num) {
assert(dest != NULL && src != NULL);
//先判断缓冲区内存是否重叠
char* cdest = (char*)dest;
char* csrc = (char*)src;
if (csrc < cdest && cdest < csrc + num) {
//要从后往前拷贝
char* pdest = cdest + num - 1;
char* psrc = csrc + num - 1;
for (int i = 0; i < num; i++) {
*pdest = *psrc;
pdest--;
psrc--;
}
}
else {
memcpy(dest, src, num);
}
return dest;
}
int main() {
char str[100] = "aaaaabbbbbeeeeeddddd";
Memmove(str + 5, str + 10, 10);
printf("%s\n", str);
system("pause");
return 0;
}
模拟实现memmove
最新推荐文章于 2022-02-19 15:39:53 发布