C语言之---mommove函数的研究

0.1版本

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(char *dst, char *src,int count)
{
	assert(dst);
	assert(src);
	assert(count > 0);
	while (count--)
	{
		*dst++ = *src++;
	}
}
int main()
{
	char msg[256] = "hello world";
	char buf[256] = {0};
	memmove(buf, msg, strlen(msg));
	printf("%s", buf);
	system("pause");
	return 0;
}
0.1版本,基本实现了函数的功能,如果其他人要使用,很不方便,假如现将count结构体对象,移到另外一个地方,必须把结构体指针强转成(char*),才能正常运行。这样会很麻烦,如何解决这个问题呢,用一种特别的指针,任意类型都可以对它进行赋值,就是void*.
0.2版本:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(void *dst, void *src, int count)
{
	assert(dst);
	assert(src);
	assert(count > 0);
	while (count--)
	{
		*(char*)dst = *(char*)src;
		dst = (char*)dst + 1;
		src = (char*)src + 1;
	}
}
int main()
{
	char msg[256] = "hello world";
	char buf[256] = {0};
	memmove(buf, msg, strlen(msg));
	printf("%s", buf);
	system("pause");
	return 0;
}

当然你会问,这也是强转啊,没错。不过这一次强制转换指针却将使用者的代码,转移到库的代码里,我么可以将memmove理解为库,而将test(测试)理解为使用者。这样就可以达到一劳永逸的效果。
0.3版本:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void *memmove(void *dst, void *src, int count)
{
	assert(dst);
	assert(src);
	assert(count > 0);
	while (count--)
	{
		*(char*)dst = *(char*)src;
		dst = (char*)dst + 1;
		src = (char*)src + 1;
	}
}
int main()
{
	char msg[255] = "hello world";
	memmove(msg + 1, msg, strlen(msg) + 1);
	printf("%s", msg);
	system("pause");
	return 0;
}

测试用例会出现以下结果,这是为什么呢?有的人会说从高地址拷贝,不过发生了重叠,原因出在源地址区间和⽬的地址区间有重叠的地⽅。所以最完美的解决⽅案还是判断源地址和⽬的地址的⼤⼩,才决定到底是从⾼地址开始 拷贝还是低地址开始拷贝。
第一种情况:

第二种情况:
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h> 
void *memmove(void *dst, void *src, int count)
{
	assert(dst);
	assert(src);
	assert(count > 0);
	int ret = dst;
	if (dst <= src || (char*)src >= (char*)dst + count)
	{
		//顺序;
		while (count--)
		{
			*(char*)dst = *(char*)src;
			dst = (char*)dst + 1;
			src = (char*)src + 1;
		}
	}
	else//逆序;
	{
		dst = (char*)dst + count - 1;
		src = (char*)src + count - 1;
		while (count--)
		{
			*(char*)dst = *(char*)src;
			dst = (char*)dst + 1;
			src = (char*)src + 1;
		}
	}
	return ret;
}
int main()
{
	char msg[256] = "hello world";
	memmove(msg + 1, msg, strlen(msg) + 1);
	printf("%s", msg);
	system("pause");
	return 0;
}
结果如下:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值