结论,strncmp不能在比较字符数组中同一位置可能均为0x00时使用。
#include <string.h>
int STRNCMP(const char *s1, const char *s2, size_t n)
{
unsigned char c1 = '\0';
unsigned char c2 = '\0';
if (n >= 4)
{
size_t n4 = n >> 2;
do
{
c1 = (unsigned char)*s1++;
c2 = (unsigned char)*s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char)*s1++;
c2 = (unsigned char)*s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char)*s1++;
c2 = (unsigned char)*s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char)*s1++;
c2 = (unsigned char)*s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
} while (--n4 > 0);
n &= 3;
}
while (n > 0)
{
c1 = (unsigned char)*s1++;
c2 = (unsigned char)*s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
n--;
}
return c1 - c2;
}
问题出现在执行下面的程序,字符不同但结果为0,找到源码一看便知:当比较的字符均为0x00
会以 return 0
结束,和字符全部相同结果一致。
int main()
{
char a[16] = {0xeb, 0x20, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xbe};
char b[16] = {0xeb, 0x20, 0x1, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xbe};
int res = STRNCMP(a, b, 16);
printf("%d\n", res);
return 0;
}
标签:strncmp,++,0x0,0x00,unsigned,char,源码,c2,c1
From: https://www.cnblogs.com/j-c-y/p/17850787.html