Chinaunix首页 | 论坛 | 博客
  • 博客访问: 134357
  • 博文数量: 51
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 540
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-21 12:33
文章分类

全部博文(51)

文章存档

2011年(1)

2010年(5)

2009年(1)

2008年(12)

2007年(32)

我的朋友

分类: C/C++

2008-02-23 22:45:39

有好几个公司的面试题都有memcpy与memmove的区别这么一道题,在这里我列出来强调一下。

它们的用法如下:

void*   memcpy(void* dest, void* source, unsigned count);  
void*   memmove(void* dest, void* source, unsigned count);

功能都是从source所指向的数组中拷贝count个字符到dest指向的数组中去. 区别是如果source和dest这两个数组重叠,memmove可以正确地拷贝到dest中去,而memcpy则执行非法。

如下的例子可以很好的说明这一点


#include <memory.h>
#include <string.h>
#include <stdio.h>
 
char string1[60] = "The quick brown dog jumps over the lazy fox";
char string2[60] = "The quick brown fox jumps over the lazy dog";

main()
{
  printf( "Function:\tmemcpy without overlap\n" );
  printf( "Source:\t\t%s\n", string1 + 40 );
  printf( "Destination:\t%s\n", string1 + 16 );
  memcpy( string1 + 16, string1 + 40, 3 );
  printf( "Result:\t\t%s\n", string1 );
  printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );
 
  /* Restore string1 to original contents */
  memcpy( string1 + 16, string2 + 40, 3 );
 
  printf( "Function:\tmemmove with overlap\n" );
  printf( "Source:\t\t%s\n", string2 + 4 );
  printf( "Destination:\t%s\n", string2 + 10 );
  memmove( string2 + 10, string2 + 4, 40 );
  printf( "Result:\t\t%s\n", string2 );
  printf( "Length:\t\t%d characters\n\n", strlen( string2 ) );
 
  printf( "Function:\tmemcpy with overlap\n" );
  printf( "Source:\t\t%s\n", string1 + 4 );
  printf( "Destination:\t%s\n", string1 + 10 );
  memcpy( string1 + 10, string1 + 4, 40 );
  printf( "Result:\t\t%s\n", string1 );
  printf( "Length:\t\t%d characters\n\n", strlen( string1 ) );
}



以上的程序执行结果如下:

/home/jx/example $ ./test
Function:    memcpy without overlap
Source:        fox
Destination:    dog jumps over the lazy fox
Result:        The quick brown fox jumps over the lazy fox
Length:        43 characters

Function:    memmove with overlap
Source:        quick brown fox jumps over the lazy dog
Destination:    brown fox jumps over the lazy dog
Result:        The quick quick brown fox jumps over the lazy dog  <== right
Length:        49 characters

Function:    memcpy with overlap
Source:        quick brown dog jumps over the lazy fox
Destination:    brown dog jumps over the lazy fox
Result:        The quick quick quick quick quick quick quick quic <== error
Length:        50 characters

/home/jx/example $

memmove可以针对特殊情况进行处理, 因此速度比memcpy慢


阅读(891) | 评论(0) | 转发(0) |
0

上一篇:SCTP编程

下一篇:教你理解复杂的C/C++声明

给主人留下些什么吧!~~