有好几个公司的面试题都有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慢
阅读(898) | 评论(0) | 转发(0) |