字符串拷贝:memcpy 和memmove

1908阅读 2评论2012-11-15 todaygood
分类:C/C++

字符串拷贝,一般用memcpy就行了

但如果是一个字符串从自身的某一个位置 copy到另外一个位置时,就涉及到重叠(overlap)的情景,这时不能使用memcpy,

要使用一个临时数组,存到这个临时数组中,然后memcpy(dst, 临时数组)

上述这个过程,有现成的函数memmove,它能处理这种情景。

 

 

#include #include <string.h> #include char string1[60] = "The quick brown dog jumps over the lazy fox"; char string2[60] = "The quick brown fox jumps over the lazy dog"; /* 1 2 3 4 5 * 12345678901234567890123456789012345678901234567890 */ void main( void ) { 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 ) ); }   在linux下的结果是: Vsles11:/mnt/Pub/1 # ./linux_memmove 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 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 quicn dog jumps over the lazy laz Length: 50 characters .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
上一篇:制作纯净64位winpe
下一篇:寻找局域网内可以ping通的机器

文章评论