C語言之memcmp函數

【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


發佈了90 篇原創文章 · 獲贊 68 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章