关于memmove函数的实现

本文详细解析了memmove函数的工作原理,包括其如何处理源和目标内存区域重叠的情况,并通过一个具体的C语言示例展示了正向和反向拷贝的过程。
 原型:  void *memmove( void* dest, const void* src, size_tcount );

#include<string.h>
由src所指内存区域复制count个字节到dest所指内存区域。

src和dest所指内存区域可以重叠,但复制后dest内容会被更改。函数返回指向dest的指针。

Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

memmove的处理措施:

(1)当源内存的首地址等于目标内存的首地址时,不进行任何拷贝
(2)当源内存的首地址大于目标内存的首地址时,实行正向拷贝
(3)当源内存的首地址小于目标内存的首地址时,实行反向拷贝

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<assert.h>

void *mymemmove(void *dest,const void *src,size_t count);
int main()
{
	char pubil[100] = "helloworld123456456";
	char *dest = pubil+4;
	char *src = pubil + 2;
	int len = 6;
	printf("main(before)dest = %s\r\n",dest);
	printf("main(before)src = %s\r\n",src);
	//dest = memmovedest(dest,src,len);
	dest = mymemmove(dest,src,len);
	printf("dest = %s\r\n",dest);
	return 0;
}



void *mymemmove(void *dest,const void *src,size_t count)
{
	char *ret=(char *)dest;//注意这里,要返回首地址
	char *dest_t=(char *)dest;
	char *src_t=(char *)src;
	assert( NULL !=src && NULL !=dest);//在这里有必要判断一下,很多人都习惯性省略
	
	if (dest_t<=src_t || dest_t>=src_t+count)
	{
        while(count--)
		{
			*dest_t++ = *src_t++;
		}
	}
	else
	{
		dest_t+=count-1;
		src_t+=count-1;
		while(count--)
		{
			*dest_t-- = *src_t--;
		}
	}
	return ret;
}

运行结果如下:

gec@ubuntu:914$ gcc memmove.c  -o memmove
gec@ubuntu:914$ ./memmove
main(before)dest = oworld123456456
main(before)src = lloworld123456456
dest = llowor123456456

思考:如果主函数定义的数组是这样定义的,会有什么不同?

char pubil[100] = "helloworld123456456";
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值