memmove and memcpy

[b][size=large][align=center]memmove and memcpy[/align][/size][/b]

字符串的拷贝函数memmove and memcpy,有什么区别?

来自MSDN上的:
1.memmove:

Copies count bytes (wmemmove) or characters (wmemmove) from src to dest. If some regions of the source area and the destination overlap, both functions ensure that the original source bytes in the overlapping region are copied before being overwritten.

2.memcpy:

memcpy copies count bytes from src to dest; wmemcpy copies count wide characters (two bytes). If the source and destination overlap, the behavior of memcpy is undefined. Use memmove to handle overlapping regions.


当src和 dest有重叠区域时,用memmove可以实现字符串的拷贝,但是另外一个函数memcpy却不可完成。

memmove 的效率低于memcpy。

3.在利用memmove and memcpy进行字符串拷贝时,要注意源字符串的长度,即要把源字符串的'/0'字符拷贝进去。

[/code="c++']
/* memcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1);
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
[/code]

输出:
str1: Sample string
str2: Sample string
str3: copy successful

代码修改如下:
[/code="c++']
/* memcpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
[b] memcpy (str2,str1,strlen(str1));[/b]
[b] memcpy (str3,"copy successful",15);[/b]
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
[/code]
输出为:
str1: Sample string
str2: Sample string烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫蘏ample string
str3: copy successful烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫蘏ample string烫烫烫烫烫烫
烫烫烫烫烫烫烫烫烫烫烫蘏ample string

原因何在?
memcpy (str2,str1,strlen(str1));这句只是拷贝了Sample string,并没有拷贝字符串的结束符号'\0',才导致此结果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值