C语言:memmove的实现

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

void* my_memmove(void* dest, const void*str, size_t count)
{
 assert(dest != NULL&str != NULL);
 char*d = (char*)dest;
 const char*s = (const char*)str;
 size_t n = count;
 if (dest > str)
 {
  while (count--)
  {
   *(d+count) = *(s+count);
  }
  
 }
 
 else
 {
  while (n--)
  {
   *d++ = *s++;
  }
 }
 return dest;

}
int main()
{
 int i = 0;
 int arr1[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
 int arr2[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
 int arr3[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 my_memmove(arr1, arr2 ,16);
 my_memmove(arr3 + 2, arr3, 16);
 printf("正常情况");
 for (i = 0; i < (sizeof arr1 / sizeof arr1[0]); i++)
 {
  printf("%d", arr1[i]);
 }
 printf("\n");
 printf("叠加情况");
 for (i = 0; i < (sizeof arr3 / sizeof arr3[0]); i++)
 {
  printf("%d", arr3[i]);
 }

 system("pause");
 return 0;
}

注意在叠加状态下,应该从后到前拷贝。

正常情况下,从前到后。

猜你喜欢

转载自blog.csdn.net/qq_43647265/article/details/86175743