gpt4 book ai didi

c - 为什么 memcmp() 相差 1 时返回 256?

转载 作者:行者123 更新时间:2023-11-30 20:48:33 32 4
gpt4 key购买 nike

所以我必须使用 C 重新创建 memcmp() 函数,并且我的函数按预期工作。它返回两个字符串中第一个不匹配的字符的差异。

我的功能:

int ft_memcmp(const void *s1, const void *s2, size_t n)
{
unsigned char *ptr1;
unsigned char *ptr2;

ptr1 = (unsigned char *)s1;
ptr2 = (unsigned char *)s2;
while (n && (*ptr1 == *ptr2))
{
ptr1++;
ptr2++;
n--;
}
if (n == 0)
return (0);
else
return (*ptr1 - *ptr2);
}

我的主要:

int main(void)
{
const char *s1 = "acc";
const char *s2 = "abc";
int res;

res = memcmp(s1, s2, 3);
printf("%i\n", res);

return (0);
}

所以这个 main 将返回 256,但是如果你使用我的函数(ft_memcmp)你会得到 1。显然差异是 1 而不是 256,但是为什么原始函数返回 256?相差 2,我得到 512...

最佳答案

Why does memcmp() return 256 for a difference of 1?

首先,正如 @where_is_tftp 所回答的,唯一的事情memcmp()需要返回的是0 ,比较一些正数和一些负数。

256 而不是 1 - 当然是因为优化。

很好memcmp()利用使用比 char 更宽的类型进行比较尽其所能。

示例:考虑对齐和总长度后,第一次比较(使用 32 位 unsigned )发现差异,不是 1 的位置(位 0),而是 256 的后位(位 8)。由于返回 256 与 1 一样有效,因此无需简化。请记住memcmp()是特定于平台的,它的实现可以做 C 代码不能做的事情 - 比如安全地访问数组外部。其他细节此处省略。

    byte 3         2        1        0
don't care 'c' 'c' 'a'
- don't care 'c' 'b' 'a'
-----------------------------------
= don't care 0 1 0
& 0 0xFF 0xFF 0xFF
-----------------------------------
= 0 0 1 0 --> 256

关于c - 为什么 memcmp() 相差 1 时返回 256?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191355/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com