我正在尝试制作哈希码函数。
但是,我得到的随机数不等于示例,我无法确定为什么(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/