原型: 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)当源内存的首地址小于目标内存的首地址时,实行反向拷贝
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<assert.h>
void *mymemmove(void *dest,const void *src,size_t count);
int main()
{
char pubil[100] = "helloworld123456456";
char *dest = pubil+4;
char *src = pubil + 2;
int len = 6;
printf("main(before)dest = %s\r\n",dest);
printf("main(before)src = %s\r\n",src);
//dest = memmovedest(dest,src,len);
dest = mymemmove(dest,src,len);
printf("dest = %s\r\n",dest);
return 0;
}
void *mymemmove(void *dest,const void *src,size_t count)
{
char *ret=(char *)dest;//注意这里,要返回首地址
char *dest_t=(char *)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;
}
运行结果如下:
gec@ubuntu:914$ gcc memmove.c -o memmove
gec@ubuntu:914$ ./memmove
main(before)dest = oworld123456456
main(before)src = lloworld123456456
dest = llowor123456456
思考:如果主函数定义的数组是这样定义的,会有什么不同?
char pubil[100] = "helloworld123456456";