【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:
[cpp] view plain copy
- //#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);
- 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;
- }
- 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
memcmp按位元組比較,可以設定比較的位數
strcmp按字元比較,隻能比較整個字元串
都是用ASCII碼進行比較,效率在數量級上不會相差太大的