深入理解memmove()与memcpy()的区别以及实现方法
// MemMove.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void* memmove(void* dest, const void* src, size_t n)
{
if (n <= 0)
{
cout << "Invalid count number." << endl;
}
if (dest == NULL || src == NULL)
{
cout << "The dest or src address is null." << endl;
}
if (dest == src)
{
cout << "The dest equals src." << endl;
}
if ((char*)dest <= (char*)src || (char*)dest >= (char*)src + n)
{//对应图中2,3,4三种情况,赋值过程中,src中未使用的不会被覆盖
char* de = (char*)dest;
const char* sr = (const char*)src;
while (n--)
{
*de++ = *sr++;
}
}
else
{//对应图中的第一种情况
char* de = (char*)dest + n -1;
const char* sr = (const char*)src + n - 1;
while (n--)
{
*de-- = *sr--;
}
}
return dest;
}
void* memmcpy(void* dest, const void* src, size_t n)
{
if (n <= 0)
{
cout << "Invalid count number." << endl;
}
if (dest == NULL || src == NULL)
{
cout << "The dest or src address is null." << endl;
}
if (dest == src)
{
cout << "The dest equals src." << endl;
}
char* de = (char*)dest;
const char* sr = (const char*)src;
while (n--)
{
*de++ = *sr++;
}
return dest;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* p = "hello,world";
char dest[12] = {0};
char *q = (char*)memmove(dest,p,5);
cout << dest << endl;
cout << q << endl;
return 0;
}