几个典型的内存拷贝及字符串函数实现
返回void *支持链式操作,参数类型是void *以支持任意类型的指针,输入参数加上const修饰,最好加上assert对输入输出指针进行非NULL判断
void* memcpy( void *dest, const void *src, size_t count )
{
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";
memcpy( str+1, str+0, 9 );
cout << str << endl;
memcpy( str, str+5, 5 );
cout << str << endl;
system( "Pause" );
return 0;
}
结果:
strcmp():
Int simple_strcmp (const char *s1, const char *s2)
{ int ret;
while ((ret = *(unsigned char *) s1 - *(unsigned char *) s2++) == 0
&& *s1++);
return ret;
}
memcmp():
int simple_memcmp (const char *s1, const char *s2, size_t n)
{ int ret = 0;
while (n--&& (ret = *(unsigned char *) s1++ - *(unsigned char *) s2++) == 0);
return ret;
}
strcmp只判断s1的‘/0’,没有长度的控制;memcmp有长度参数n的控制
memcpy():
char *simple_memcpy (char *dst, const char *src, size_t n)
{ char *ret = dst;
while (n--)
*dst++ = *src++;
return ret;
}
直接的内存之间的copy,不处理内存重叠的情况。
strcpy():
char *simple_strcpy (char *dst, const char *src)
{ char *ret = dst;
while ((*dst++ = *src++) != '/0'); //相当简约,一句话即搞定
return ret;
}
与memcpy区别就是对'/0'作为结束符
strncpy():
char *simple_strncpy (char *dst, const char *src, size_t n)
{
char *ret = dst;
while (n--)
{
if ((*dst++ = *src++) == '/0')
{
while (n--)
*dst++ = '/0';
return ret;
}
}
return ret;
}
n和‘/0'都作为结束的控制符。如果n过大,则后面全补'/0'
文章出处:http://www.diybl.com/course/3_program/c++/cppjs/20081013/150498.html
0012345678
4567845678