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的高效實現方式。