/*
memcmp是比较内存区域buf1和buf2的前count个字节。该函数是按字节比较的。
*/
#include <stdio.h>
int memcmp_c(const void *buf1, const void *buf2, size_t count);
int main(void)
{
char buffer1[] = "luohan";
char buffer2[] = "luo";
int n;
n = memcmp_c(buffer1, buffer2, 2);
if(n > 0)
printf(" '%s' is greater than '%s'\n", buffer1, buffer2);
else if(n == 0)
printf(" '%s' is the same as '%s'\n", buffer1, buffer2);
else
printf(" '%s' is less than '%s'\n", buffer1, buffer2);
}
int memcmp_c(const void * buf1, const void *buf2, size_t count)
{
if(!count)
return 0;
// count 首先减一是因为在return中已经进行了一次比较。
// 如果count--,将会多比较一次。
while( --count && *(char*)buf1 == *(char*)buf2 )
{
buf1 = (char*)buf1 + 1;
buf2 = (char*)buf2 + 1;
}
return ( *((unsigned char*)buf1) - *((unsigned char*)buf2) );
}
memcmp
最新推荐文章于 2024-09-23 22:08:54 发布