c语言 - 无符号整数溢出不"wrap around"



我从整数溢出维基中读到了以下行:

而无符号整数溢出导致数字减少取模 2的幂,意味着无符号整数"环绕"在 溢出。

有下面的代码,我正在尝试创建一个哈希函数并遇到 int 溢出情况。我试图通过使用unsigned int来缓解它,但它不起作用,我能够看到负值。

我知道我可以以其他方式处理它并且它可以工作,如我的代码注释所示 - Comment 2: .但这是正确的方式吗,为什么unsigned int没有缠绕和溢出?

int hash(char *word) {
    char *temp = word;
    unsigned int hash = 0; // Comment 1: I tried to handle int overflow using "unsigned" int.
    while (*word != '') {
        // Comment 2: This works but I do not want to go this way. 
        //while ((hash * PRIME_MULTIPLIER) < 0) {
        //    hash = (hash * PRIME_MULTIPLIER) + 2147483647;
        //}
        hash = hash * PRIME_MULTIPLIER + *word;
        word++;
    }
    printf("Hash for %s is %dn", temp, hash);
    return hash;
}

您使用了错误的格式说明符来printf 。 对于unsigned int,您应该使用%u而不是%d

此外,您应该返回unsigned int而不是int

最新更新