1、memcmp含义less
Compare characters in two buffers.ide
int memcmp( const void* buf1, const void* buf2, size_t count );函数
inline int wmemcmp ( const wchar_t* buf1, const wchar_t* buf2, size_t count);spa
Parametersblog
Return Value | Relationship of First count Bytes of buf1 and buf2 |
---|---|
< 0 | buf1 less than buf2 |
0 | buf1 identical to buf2 |
> 0ip |
buf1 greater than buf2内存 |
2、memcmp与strncmp的区别ci
int memcmp(const void * cs,const void * ct,size_t count)
{ 字符串
const unsigned char *su1, *su2;
int res = 0;
for( su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
if ((res = *su1 - *su2) != 0)
break;
return res;
}
int strncmp(const char * cs,const char * ct,size_t count)
{
register signed char __res = 0;
while (count) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
break;
count--;
}
return __res;
} io
一、这两个函数的差异其实仍是挺大的,差异在这里:
对于memcmp(),若是两个字符串相同并且count大于字符串长度的话,memcmp不会在\0处停下来,会继续比较\0后面的内存单元,直到_res不为零或者达到count次数。
对于strncmp(),因为((__res = *cs - *ct++) != 0 || !*cs++)的存在,比较一定会在最短的字符串的末尾停下来,即便count还未为零。具体的例子:
char a1[]="ABCD";
char a2[]="ABCD";
对于memcmp(a1,a2,10),memcmp在两个字符串的\0以后继续比较
对于strncmp(a1,a2,10),strncmp在两个字符串的末尾停下,再也不继续比较。
因此,若是想使用memcmp比较字符串,要保证count不能超过最短字符串的长度,不然结果有多是错误的。
二、strncmp("abcd", "abcdef", 6) = 0。比较次数是同样的: memcmp:在比较到第5个字符也就是'\0',*su1 - *su2的结果显然不等于0,因此知足条件跳出循环,不会再进行后面的比较。我想在其余状况下也同样。 strncmp:一样的道理再比较到第5个字符时结束循环,其实strncmp中“!*cs++”彻底等同于“!*ct++”,其做用仅在于当两个字符串相同的情形下,防止多余的比较次数。