`
weihe6666
  • 浏览: 429973 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

memmove and memcpy

    博客分类:
  • C++
阅读更多
memmove and memcpy


字符串的拷贝函数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;
}


输出:
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];
  memcpy (str2,str1,strlen(str1));
  memcpy (str3,"copy successful",15);
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}

输出为:
str1: Sample string
str2: Sample string烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫蘏ample string
str3: copy successful烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫蘏ample string烫烫烫烫烫烫
烫烫烫烫烫烫烫烫烫烫烫蘏ample string

原因何在?
memcpy (str2,str1,strlen(str1));这句只是拷贝了Sample string,并没有拷贝字符串的结束符号'\0',才导致此结果。



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics