首页 > 其他 > 详细

模拟实现memcpy 与 memmove

时间:2019-03-01 12:35:44      阅读:220      评论:0      收藏:0      [点我收藏+]
模拟实现memcpy 与 memmove
1.str系列的函数只能处理字符串——>必须带有‘\0‘
2.memcpy内存处理函数:不涉及‘\0‘,需要包含头文件 string.h
3.source的内存不能超过destanation的内存大小
4.存在缓冲区的重合问题,要保证destanation指向有效的区域:可以用从右往左拷贝的方法
//memmove可以解决mencoy的缓冲区重合的问题
 1 #include<stdio.h>
 2 #include<assert.h>
 3 void Memcpy(void* destanation, const void* source, size_t num)
 4 {
 5  assert(destanation != 0);
 6  assert(source != 0);
 7  char* dest = (char*)destanation;
 8  char* sour = (char*)source;
 9  for (size_t i = 0; i < num; i++)
10  {
11   dest[i] = sour[i];
12  }
13  return destanation;
14 }
15 void Memmove(void* destanation, const char* source, size_t num)
16 {
17  assert(destanation != 0);
18  assert(source != 0);
19  char* dest = (char*)destanation;
20  char* sour = (char*)source;
21  //两种情况:
22  if (sour<dest&&sour + num>dest)
23  {
24   //1.缓冲区重合就从后往前拷贝
25   for (int i = num - 1; i >= 0; --i)
26   {
27    dest[i] = source[i];
28   }
29  }
30  else
31  {
32   //2.缓冲区没重合,代码和memcpy一样
33   Memcpy(destanation, source, num);
34  }
35 }
36 int main()
37 {
38  int arr1[4] = { 1,2,3,4 };
39  int arr2[4] = { 0 };
40  Memcpy(arr1, arr2, sizeof(arr1));
41  for (int i = 0; i < sizeof(arr1) / sizeof(int); i++)
42  {
43   printf("%d",arr2[i]);
44  }
45  return 0;
46 } 

 

模拟实现memcpy 与 memmove

原文:https://www.cnblogs.com/cuckoo-/p/10455665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!