C 库函数 - memmove()

 cpulspuls官方描述—<string.h>

描述:

memmove 函数,和memcpy一样,可以将 num 个字节的值从源指向的位置直接复制到目标指向的内存块。

不过memcpy一般用来处理2个独立的内存空间

memmove通常用来处理2块重叠的内存空间

我们可以这样说:对于重叠的内存块,使用 memmove 函数是一种更安全的方法。

声明:

void * memmove ( void * destination, const void * source, size_t num );

代码实现:

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

void* My_memmove(void* to, const void* from, size_t sz)
{
	assert(to && from);

	void* ret = to;

	if (to < from)//从前往后
	{
		while (sz--)
		{
			*(char*)to = *(char*)from;
			to = (char*)to + 1;
			from = (char*)from + 1;
		}
	}
	else//从后往前
	{
		while(sz--)//从最后位置-1开始copy
		{
			*((char*)to + sz) = *((char*)from + sz);
		}
	}
	return ret;
}

int main()
{
	int arr_1[] = {1,2,3,4,5,6,7,8,9,10};
	int i = 0;
	int sz = 0;
	sz = sizeof(arr_1) / sizeof(arr_1[0]);

	My_memmove(arr_1, arr_1+3, 20);

	for (i = 0; i < sz; i++)
	{
		printf("%d ", arr_1[i]);
	}

	return 0;
}

运行结果:

模拟实现【memmove】函数_代码实现