Memcpy按字节拷贝与按int拷贝的实现

#include
using namespace std;

#define	DbgTrace			(void*)0
#define	DbgTraceStr(s)		(void*)0
#define DbgTraceBegin		(void*)0(
#define DbgTraceEnd			);

//MemcpyBybyte
void* Memcpy(void* dest, const void* src, size_t n)
{
	if (dest == nullptr || src == nullptr || n <= 0)
		return nullptr;
	char* pdest = (char*)dest;
	const char* psrc = (const char*)src;
	if (psrc<pdest && psrc + n>pdest)
	{
		//从右往左
		pdest = pdest + n - 1;
		psrc = psrc + n - 1;
		while (n--)
		{
			*pdest-- = *psrc--;
		}
	}
	else
	{
		//从左往右
		while (n--)
		{
			*pdest++ = *psrc++;
		}
	}
	return dest;
}
void* Memcpy_int(void* dest, const void* src, size_t n)
{
	if (dest == nullptr || src == nullptr || n <= 0)
		return nullptr;
	int* pdest = (int*)dest;
	const int* psrc = (const int*)src;
	int c = n / 4;
	int m = n % 4;
	char* temp1 = nullptr;
	char* temp2 = nullptr;
	if (psrc<pdest && (const char*)psrc + n>(char*)pdest)
	{
		//从右往左
		temp1 = (char*)(pdest)+n - 1;
		temp2 = (char*)(psrc)+n - 1;
		while (m--)
		{
			*temp1-- = *temp2--;
		}
		++temp1;
		++temp2;
		pdest = (int*)temp1;
		psrc = (int*)temp2;
		--pdest;
		--psrc;
		while (c--)
		{
			*pdest-- = *psrc--;
		}
	}
	else
	{
		//从左往右
		while (c--)
		{
			*pdest++ = *psrc++;
		}
		temp1 = (char*)pdest;
		temp2 = (char*)psrc;
		while (m--)
		{
			*temp1++ = *temp2++;
		}
	}
	return dest;
}
int main()
{

	(void*)0;
	(void*)0("sd");
	(void*)0("sdas%d",1);
	return 0;
}

你可能感兴趣的:(C++)