关于memmove函数的实现

 原型:  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";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值