在网上找了个题目如题目,本来以为就跟字符串的复制一样,一个while就行了,看了答案才知道,内存处理没有那么简单,因为我们时刻要小心内存处理问题。
但是看了代码,想了半天才想同原理,真是惭愧啊! 本来打算准备用个坐标轴来描述这个原理的,只是我个人比较懒的去画,就简单的说下,以明示自己下次不能犯这样的错误了。 方法一: void* mymemcpy( void *dest, const void *src, size_t count )
{
char* pdest = static_cast
const char* psrc = https://www.it610.com/article/static_cast
if( pdest>psrc && pdest{
for( size_t i=count-1;
i!=-1;
--I )
pdest[i] = psrc[i];
}
else
{
for( size_t i=0;
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;
}
推荐阅读
- c/c++|有感 Visual Studio 2015 RTM 简介 - 八年后回归 Dot Net,终于迎来了 Mvc 时代,盼走了 Web 窗体时代...
- C/C++|C/C++ basis 02
- Qt实战|Qt+OpenCV联合开发(二十一)--图像翻转与旋转
- Qt实战|Qt+OpenCV联合开发(十四)--图像感兴趣区域(ROI)的提取
- Qt实战|Qt+OpenCV联合开发(十三)--通道分离与合并
- opencv|Qt+OpenCV联合开发(十六)--图像几何形状绘制
- Qt实战|Qt+OpenCV联合开发(十七)--随机数与随机颜色
- SNAT的MASQUERADE地址选择与端口选择
- IPTABLES的连接跟踪与NAT分析
- IPVS分析