int memcmp(const void *cs, const void *ct, size_t count)
{
const unsigned char *su1, *su2;
int res = 0;
for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
if ((res = *su1 - *su2) != 0)
break;
return res;
}
void *memset(void *s, int c, size_t n)
{
char * tmp = (char *)s;
while(n-- > 0)
*tmp++ = c;
return s;
}
/***
*char *memchr(buf, chr, cnt) - search memory for given character.
*
*Purpose:
* Searches at buf for the given character, stopping when chr is
* first found or cnt bytes have been searched through.
*
*Entry:
* void *buf - memory buffer to be searched
* int chr - character to search for
* size_t cnt - max number of bytes to search
*
*Exit:
* returns pointer to first occurence of chr in buf
* returns NULL if chr not found in the first cnt bytes
*
*Exceptions:
*
*******************************************************************************/
void * memchr (const void * buf,int chr,size_t cnt)
{
while ( cnt && (*(unsigned char *)buf != (unsigned char)chr) ) {
buf = (unsigned char *)buf + 1;
cnt--;
}
return(cnt ? (void *)buf : NULL);
}
以上是memcmp,memset,memchr 函数的算法实现,如果相对算法优化,请参考前一章节memcpy函数的处理方式,这里不展开讨论了,另外提醒读者一个诀窍,mem系列函数通常都带3个参数,且第三个参数一般都指的是待操作的内存长度,有些人很容易弄混memset函数的第2以及第三个参数的意义。通过这个诀窍我们知道,memset第2个参数是指初始化初值,第三个参数指内存长度。至此,我们讨论了string.h中所有的函数,并且学习了glibc以及crt的高效实现方式。