写一个函数,完成内存之间的拷贝

在网上找了个题目如题目,本来以为就跟字符串的复制一样,一个while就行了,看了答案才知道,内存处理没有那么简单,因为我们时刻要小心内存处理问题。
但是看了代码,想了半天才想同原理,真是惭愧啊! 本来打算准备用个坐标轴来描述这个原理的,只是我个人比较懒的去画,就简单的说下,以明示自己下次不能犯这样的错误了。 方法一: void* mymemcpy( void *dest, const void *src, size_t count )
{
char* pdest = static_cast( dest );
const char* psrc = https://www.it610.com/article/static_cast( src );
if( pdest>psrc && pdest{
for( size_t i=count-1; i!=-1; --I )
pdest[i] = psrc[i];
}
else
{
for( size_t i=0; ipdest[i] = psrc[i];
}
return dest;
}
int main( void )
{
char str[] = "0123456789";
mymemcpy( str+1, str+0, 9 );
cout << str << endl;

system( "Pause" );
return 0;
} 方法二: void* mymemcpy (void* dest, void* source, size_t count) {
void* ret = dest;

if (dest <= source || dest >= (source + count))
{
//Non-Overlapping Buffers
//copy from lower addresses to higher addresses

while (count --)
*dest++ = *source++;
}
else
【写一个函数,完成内存之间的拷贝】{
//Overlapping Buffers
//copy from higher addresses to lower addresses

dest += count - 1;
source += count - 1;
while (count--)
*dest-- = *source--; l
}
return ret;
}

另一种实现:这个方法我觉得是最有创新的方法,赞一个。写出这样的代码的人要有多请的内力啊!
void* mymemcpy( void* dest, const void* src, size_t count )
{
char* d = (char*)dest;
const char* s = (const char*)src;
//int n = (count + 7) / 8; // count > 0 assumed
int n = count >> 3;
switch( count & 7 )
{
do {*d++ = *s++;
case 7:*d++ = *s++;
case 6:*d++ = *s++;
case 5:*d++ = *s++;
case 4:*d++ = *s++;
case 3:*d++ = *s++;
case 2:*d++ = *s++;
case 1:*d++ = *s++;
case 0} //while (--n > 0);
while (n-- > 0)
}

return dest;
}

    推荐阅读