memset,memcpy,memmove,strcpy,strcat,strcmp的实现(其实很简单,每个程序都只有几行代码)

时间:2021-12-05 09:58:58

面试中的几个小问题

1.对stl中list封装(参考1);

2.对重要C函数实现(参考2);

//memset

void *memset(void *buffer, int c, int count)

{

char* p = (char*)buffer;

while(count--)

*p++ = (char)c;

return buffer;

}

//memcpy

void * memcpy(void *dst,const void *src,int count)

{

void * ret = dst;

while (count--)

{

*(char *)dst = *(char *)src;

dst = (char *)dst + 1;

src = (char *)src + 1;

}

return(ret);

}

//memmove

/**//*

memmove()由src所指定的内存区域赋值count个字符到dst所指定的内存区域。

src和dst所指内存区域可以重叠,但复制后src的内容会被更改。函数返回指向dst的指针。

*/

void * memmove(void * dst,const void * src,int count)

{

void * ret = dst;

if (dst <= src || (char *)dst >= ((char *)src + count))

{

while (count--)

{

*(char *)dst = *(char *)src;

dst = (char *)dst + 1;

src = (char *)src + 1;

}

}

else

{

dst = (char *)dst + count - 1;

src = (char *)src + count - 1;

while (count--)

{

*(char *)dst = *(char *)src;

dst = (char *)dst - 1;

src = (char *)src - 1;

}

}

return(ret);

}

char * __cdecl strcpy(char * dst, const char * src)

{

char * cp = dst;

while( *cp++ = *src++ )    ;

return( dst );

}

char * strcat (char * dst, char * src)

{

char * cp = dst;

while( *cp )

++cp;   /**//* Find end of dst */

while( *cp++ = *src++ )

/**//* Copy src to end of dst */

return( dst );

}

int strlen(const char * str )

{

const char *p = str;

while( *p++ ) ;

return( (int)(p - str - 1) );

}

//strcmp

int strcmp(const char *string1, const char *string2 )

{

int ret;

while(    ( ret=*(unsigned char *)string1++ -*(unsigned char *)string2++)==0 &&   string1  );

return ret;

}

3.用C 写一个输入的整数,倒着输出整数的函数,要求用递归方法

void fun( int nNum)

{

printf( "%d", nNum%10 );

nNum /= 10;

if(nNum<=0)

{

return;

}

fun( nNum );

}

4.其他

参考

1. Clist封装函数

STL介绍 http://blog.csdn.net/sunny_chenpeng/article/details/5449426

介绍Clist  http://blog.csdn.net/dream199029/article/details/4221577

封装 http://www.cppblog.com/changshoumeng/archive/2010/05/08/114822.aspx

2. C函数重写 http://www.cppblog.com/changshoumeng/archive/2010/05/08/114822.aspx

http://blog.csdn.net/wsh6759/article/details/7048106