本文主要是介绍memmove使⽤和模拟实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一:memmove的使⽤
这是memmove在库里的定义,具体可在cplusplus.com查看
void * memmove ( void * destination, const void * source, size_t num )
• 和memcpy的差别就是memmove函数处理的源内存块和⽬标内存块是可以重叠的。
• 如果源空间和⽬标空间出现重叠,就得使⽤memmove函数处理。
代码:
include <stdio.h>
#include <string.h>
int main(){ int arr1[] = { 1,2,3,4,5,6,7,8,9,10 }; memmove(arr1+2, arr1, 20); int i = 0; for (i = 0; i < 10; i++) { printf("%d ", arr1[i]); }return 0; }
输出的结果:1 2 1 2 3 4 5 8 9 1
二:memmove的模拟实现
代码1:
void*my_memmove(void* dst, const void* src, size_t count)
{void* ret = dst;if (dst <= src || (char*)dst >= ((char*)src + count)) {while (count--) {*(char*)dst = *(char*)src;dst = (char*)dst + 1;src = (char*)src + 1;}}else {dst = (char*)dst + count - 1;src = (char*)src + count - 1;while (count--) {*(char*)dst = *(char*)src;dst = (char*)dst - 1;src = (char*)src - 1;}}return(ret);
}
int main()
{int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };my_memmove(arr+2, arr , 20);for (int i = 0; i < 10; i++){printf("%d ", arr[i]);//1 2 1 2 3 4 5 8 9 10,结果}return 0;
}
代码2:
函数也可以这样写,结果一样
void* my_memmove(void* arr1, const void* arr2, size_t num)
{if (arr1 < arr2){while (num--){*(char*)arr1 = *(char*)arr2;arr1 = (char*)arr1 + 1;arr2 = (char*)arr2 + 1;}}if (arr1 > arr2){// arr1 = (char*)arr1 + num - 1;// arr2 = (char*)arr2 + num - 1;while (num--){*((char*)arr1+num-1)=*((char*)arr2+num-1);//法1 //取消注释就是另一种方法// *(char*)arr1 = *(char*)arr2;// arr1 = (char*)arr1 - 1;// arr2 = (char*)arr2 - 1;}}
}
这篇关于memmove使⽤和模拟实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!