【C语言】memcmp函数的实现

memcmp是比较 内存 区域buf1和buf2的前count个字节。该 函数 是按 字节 比较的。
 
头文件
#include
 
int memcmp(const void *buf1, const void *buf2, unsigned int count);
比较内存区域buf1和buf2的前count个字节。
 
头文件
#include 或#include
 
返回值
当buf1
当buf1=buf2时,返回值=0
当buf1>buf2时,返回值>0
 
所以该函数的功能实现为:
#include
#include
int my_memcmp(char *str1,char *str2,int len)
{
	assert(str1);
	assert(str2);
	while(len--)
	{
	while(*str1==*str2)
	{
		if(*str1=='\0')
			return 0;
	
			str1++;
			str2++;
	
	}
	}
	if(*str1>*str2)
		return 1;
	if(*str1<*str2)
		return -1;
}


int main()
{
	char *p="adcc";
	char *q="bac";
	printf("%d\n",my_memcmp(p,q,1));
	return 0;
}

运行结果如图所示:

你可能感兴趣的:(【C语言】memcmp函数的实现)