c - C 中哈希码的递归

标签 c recursion hash

我正在尝试制作哈希码函数。

但是,我得到的随机数不等于示例,我无法确定为什么(5是最大长度,所以不需要动态内存分配)

最佳答案

来自 strncpy documentation :

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

所以你想做的:

strncpy(new, str, l - 1);
new[l - 1] = 0;

但您也可以避免使用辅助函数创建新字符串:

unsigned long hash_helper(const char* str, int len){
    if (len == 0) return 0;
    return hash_helper(str, len - 1) * 65599 + str[len - 1]; 
}

unsigned long hash(const char* str){
    return hash_helper(str, strlen(str));
}

关于c - C 中哈希码的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210098/

相关文章:

c - 在这种情况下,如何链接库函数?

c++ - 在不使用图形的情况下以最小产品从第一个索引到最后一个索引?

cocoa - 缓存 URL - 创建适当的 NSString 表示

git - 在不归档的情况下将 Git SHA1 信息扩展到 checkin 中?

c - 如何将结构体值传递到打印函数中,然后在 main 中调用它? - C语言

c - 错误 : not a member of structure or union, 导致内存泄漏

c - 在 C 中传递结构体指针数组作为引用

delphi - 使用递归函数进行数制转换 - 返回值错误

c++ - 包含自身实例化的模板,C++ 中的递归

ruby - 初始化哈希