一、memcmp含義
Compare characters in two buffers.
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);
Parameters
- buf1 : First buffer.
- buf2 : Second buffer.
- count : Number of characters.
- Return Values : The return value indicates the relationship between the buffers.
Return Value | Relationship of First count Bytes of buf1 and buf2 |
---|---|
< 0 | buf1 less than buf2 |
0 | buf1 identical to buf2 |
> 0 |
buf1 greater than buf2 |
二、memcmp與strncmp的區別
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;
}
1、這兩個函數的差別其實還是挺大的,差別在這裏:
對於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不能超過最短字符串的長度,否則結果有可能是錯誤的。
2、strncmp("abcd", "abcdef", 6) = 0。比較次數是一樣的:
memcmp:在比較到第5個字符也就是'\0',*su1 - *su2的結果顯然不等於0,所以滿足條件跳出循環,不會再進行後面的比較。我想在其他情況下也一樣。
strncmp:同樣的道理再比較到第5個字符時結束循環,其實strncmp中“!*cs++”完全等同於“!*ct++”,其作用僅在於當兩個字符串相同的情形下,防止多餘的比較次數。