模拟实现memcpy 与 memmove

模拟实现memcpy 与 memmove
1.str系列的函数只能处理字符串——>必须带有''
2.memcpy内存处理函数:不涉及'',需要包含头文件 string.h
3.source的内存不能超过destination的内存大小
4.存在缓冲区的重合问题,要保证destination指向有效的区域:可以用从右往左拷贝的方法
//memmove可以解决mencoy的缓冲区重合的问题
 1 #include<stdio.h>
 2 #include<assert.h>
 3 void Memcpy(void* destination, const void* source, size_t num)
 4 {
 5  assert(destination != 0);
 6  assert(source != 0);
 7  char* dest = (char*)destination;
 8  char* sour = (char*)source;
 9  for (size_t i = 0; i < num; i++)
10  {
11   dest[i] = sour[i];
12  }
13  return destination;
14 }
15 void Memmove(void* destination, const char* source, size_t num)
16 {
17  assert(destination != 0);
18  assert(source != 0);
19  char* dest = (char*)destination;
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(destination, source, num);
34  }
35 }
36 int main()
37 {
38  int arr1[4] = { 1,2,3,4 };
39  int arr2[4] = { 0 };
40  Memcpy(arr2, arr1, sizeof(arr1));
41  for (int i = 0; i < sizeof(arr1) / sizeof(int); i++)
42  {
43   printf("%d",arr2[i]);
44  }
45  return 0;
46 } 
原文地址:https://www.cnblogs.com/cuckoo-/p/10455665.html