写一个函数,完成内存之间的拷贝
在网上找了个题目如题目,本来以为就跟字符串的复制一样,一个while就行了,看了答案才知道,内存处理没有那么简单,因为我们时刻要小心内存处理问题。
{
char* pdest = static_cast<char*>( dest );
const char* psrc = static_cast<const char*>( src );
if( pdest>psrc && pdest<psrc+count )
{
for( size_t i=count-1; i!=-1; --I )
pdest[i] = psrc[i];
}
else
{
for( size_t i=0; i<count; ++I )
pdest[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* 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;
}