memmove重叠字符串拷贝的介绍和模拟实现
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
//memmove重叠内存拷贝
//用来实现重叠内存之间的数据拷贝
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr1 + 2, arr1, 20);
//1 2 1 2 3 4 5 8 9 10
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
//memmove的模拟实现
#include <assert.h>
void* my_memmove(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
if (dest < src)
{
//从前向后拷贝
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
else
{
//从后向前拷贝
while (num--)
{
*((char*)dest + num) = *((char*)src + num);//num此时为19个字节,再减减变成18,以此类推
}
}
return ret;
}
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
//my_memmove(arr1+2, arr1, 20);
//1 2 1 2 3 4 5 8 9 10
my_memmove(arr1, arr1+2, 20);
//3 4 5 6 7 6 7 8 9 10
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}