【FROM MSDN && 百科】
原型: int memcmp(const void *buf1, const void *buf2, unsigned int count);
#include<string.h>
比较内存区域buf1和buf2的前count个字节。此函数是按字节比较。
Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed
by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not。
Notice that, unlike strcmp,
the function does not stop comparing after finding a null character.
对于memcmp(),如果两个字符串相同而且count大于字符串长度的话,memcmp不会在\0处停下来,会继续比较\0后面的内存单元,如果想使用memcmp比较字符串,要保证count不能超过最短字符串的长度,否则结果有可能是错误的。
DEMO:
//#define FIRST_DEMO
#define MYMEMCMP
#ifdef FIRST_DEMO
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void)
{
char *s1="Hello, Programmers!";
char *s2="Hello, Programmers!";
int r;
r=memcmp(s1,s2,50/*strlen(s1)*/);
if (!r)
{
printf("s1 and s2 are identical!\n");
}
else if (r<0)
{
printf("s1 less than s2\n");
}
else
{
printf("s1 greater than s2\n");
}
getch();
return 0;
}
#elif defined MYMEMCMP
#include <stdio.h>
#include <conio.h>
#include <string.h>
int mymemcmp(const void *buffer1,const void *buffer2,int ccount);
void Print(char *str1,char *str2,int t);
int main(void)
{
char *str1="hel";
char *str2="hello";
Print(str1,str2,mymemcmp(str1,str2,3));
Print(str2,str1,mymemcmp(str2,str1,3));
Print(str2,str2,mymemcmp(str2,str2,3));
getch();
return 0;
}
/*FROM:http://blog.chinaunix.net/uid-20480343-id-1941630.html */
int mymemcmp(const void *buffer1,const void *buffer2,int count)
{
if (!count)
{
return 0;
}
while(count && *(char *)buffer1==*(char *)buffer2)
{
count--;
buffer1=(char *)buffer1-1;
buffer2=(char *)buffer2-1;
}
return (*((unsigned char *)buffer1)- *((unsigned char *)buffer2));
}
void Print(char *str1,char *str2,int t)
{
if (t>0)
{
printf("\n%s Upper than %s \n",str1,str2);
}
else if(t<0)
{
printf("\n%s Lower than %s \n",str1,str2);
}
else
{
printf("\n%s equal %s \n",str1,str2);
}
}
#endif
来源:CSDN
作者:hou_sky
链接:https://blog.csdn.net/hgj125073/article/details/8471616