【发布时间】:2013-11-20 20:50:51
【问题描述】:
我有一个任务是重写一些在 libc 中可用的流行 C 函数。
我正在写strcmp,当我写完并且对它感到满意时,我去检查了 libc 中的那个。
这是我的:
int ft_strcmp(const char *s1, const char *s2)
{
while (*s1 && *s1 == *s2)
{
s1++;
s2++;
}
return ((unsigned char)*s1 - (unsigned char)*s2);
}
这是 libc (https://www.opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c) 中的那个:
int
strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1); // HERE ! Why *(unsigned char *) :/ ?
}
我不明白为什么*(unsigned char *)s1 有效,我以为它不会,但它似乎真的有效!
然后我在另一个 libc (https://sourceware.org/git/?p=glibc.git;a=blob;f=string/strcmp.c;h=a4645638eb685e479b89a5e3912076329cc27773;hb=HEAD) 中找到了这个实现
int
strcmp (p1, p2)
const char *p1;
const char *p2;
{
const unsigned char *s1 = (const unsigned char *) p1;
const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
这也很奇怪,但出于其他原因,这个使用了我认为正确的(const unsigned char *) p1
【问题讨论】:
-
“我认为不会”——为什么不会呢?
-
为什么还要加一个 * 呢?我的意思是这 2 颗星的意义何在?
-
嗯什么?那么为什么你认为这个结构不起作用呢?第一个星号是取消引用指针的
*运算符。第二颗星(在类型转换内)是指针限定符。 -
为什么
*(unsigned char *)s1中有2个* -
在这种情况下,没有区别,但如果指针不是
char *,而是e。 G。如果代码将别名为int *,那么会有。