【FROM MSDN && 百科】
原型: void *memmove( void* dest, const void* src, size_tcount );
#include<string.h>
由src所指內存區域復制count個字節到dest所指內存區域。
src和dest所指內存區域可以重疊,但復制後dest內容會被更改。函數返回指向dest的指針。
Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
memmove的處理措施:
(1)當源內存的首地址等於目標內存的首地址時,不進行任何拷貝
(2)當源內存的首地址大於目標內存的首地址時,實行正向拷貝
(3)當源內存的首地址小於目標內存的首地址時,實行反向拷貝
//#define FIRST_DEMO //#define SECOND_DEMO #define MYMEMMOVE #ifdef FIRST_DEMO #include <stdio.h> #include <conio.h> #include <string.h> int main(void) { char s[]="Golden Global View"; memmove(s,s+7,strlen(s)+1-7);//+1是取'\0',可以去掉看下結果 printf("%s\n",s); getch(); return 0; } #elif defined SECOND_DEMO #include <stdio.h> #include <conio.h> #include <string.h> int main(void) { char str1[7]="aabbcc"; printf( "The string: %s\n", str1 ); memcpy(str1+2,str1,4); printf( "New string: %s\n", str1 ); memmove(str1+2,str1,4); printf( "New string: %s\n", str1 ); getch(); return 0; } /*output: The string: aabbcc New string: aaaabb New string: aaaaaa */ #elif defined MYMEMMOVE #include <stdio.h> #include <conio.h> #include <string.h> #include <assert.h> void *mymemmove(void *dest,const void *src,size_t coount); int main(void) { char str1[7]="aabbcc"; mymemmove(str1+2,str1,4); puts(str1); getch(); return 0; } void *mymemmove(void *dest,const void *src,size_t count) { char *ret=(char *)dest; char *dest_t=dest; char *src_t=(char *)src; assert( NULL !=src && NULL !=dest); if (dest_t<=src_t || dest_t>=src_t+count) { while(count--) { *dest_t++ = *src_t++; } } else { dest_t+=count-1; src_t+=count-1; while(count--) { *dest_t--=*src_t--; } } return ret; } #endif
void *memmove(void *dest, const void *src, size_t len);
將指針src指向的前n個字節拷貝到dest指向的前n個內存區域中。當src和desc有重復區域時,先將desc向後移,然後再進行拷貝操作.
Required Header <string.h>
void *my_memmove(void *dst,const void *src,int count)
{
char *ret;
char *dst_t;
char *src_t;
ret = (char *)dst;
if ((unsigned char*)dst <= (unsigned char*)src || \
(unsigned char *)dst >= ((unsigned char *)src + count))
{
dst_t = (char *)dst;
src_t = (char *)src;
while (count--)
{
*dst_t++ = *src_t++;
}
}
else
{
dst_t = (char *)dst + count - 1;
src_t = (char *)src + count - 1;
while (count--)
{
*dst_t-- = *src_t--;
}
}
return(ret);
}
參考資料:wenku.baidu.com/...3.html