哈希函数问题 - 添加功能
Hash function issue - adding functionality
我尝试向 djb2 哈希函数添加功能,但它似乎不喜欢这些更改。具体来说,我试图包含一个将单词(字符串)转换为小写的循环。它抛出以下两个错误:
- 从
int
分配给 char *
的指针转换不兼容的整数
- 无法递增类型
char *[45]
的值
请注意,在原始代码中 *str++
出现在 while
循环中。这是我的第一个散列 table,我对指针相当不稳定。任何关于我哪里出错的见解都将不胜感激。
// djb2 by Dan Bernstein -- slightly modified;
unsigned int hash_function(const char* str)
{
unsigned int hash = 5381;
int c;
char* string[45];
for (int i = 0; str[i] != '[=10=]'; i++)
{
string[i] = (tolower(str[i]));
}
while (c == *string++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return (hash % LISTS);
}
这个:
char* string[45];
表示"array of 45 character pointers",你应该去掉星号。
并且您不能通过递增变量来遍历数组,数组变量不能更改。您可以使用单独的指针:
const char *s = string;
while (c = *s++)
请注意,assignment 拼写为 =
,而 ==
是相等性比较,这不是您的意思。
更高效的哈希版本:
unsigned int hash_function(const char* str)
{
unsigned int hash = 5381, c;
while(c = *str++)
hash += (hash << 5) + (c | 040);
return (hash % LISTS);
}
我尝试向 djb2 哈希函数添加功能,但它似乎不喜欢这些更改。具体来说,我试图包含一个将单词(字符串)转换为小写的循环。它抛出以下两个错误:
- 从
int
分配给 - 无法递增类型
char *[45]
的值
char *
的指针转换不兼容的整数
请注意,在原始代码中 *str++
出现在 while
循环中。这是我的第一个散列 table,我对指针相当不稳定。任何关于我哪里出错的见解都将不胜感激。
// djb2 by Dan Bernstein -- slightly modified;
unsigned int hash_function(const char* str)
{
unsigned int hash = 5381;
int c;
char* string[45];
for (int i = 0; str[i] != '[=10=]'; i++)
{
string[i] = (tolower(str[i]));
}
while (c == *string++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return (hash % LISTS);
}
这个:
char* string[45];
表示"array of 45 character pointers",你应该去掉星号。
并且您不能通过递增变量来遍历数组,数组变量不能更改。您可以使用单独的指针:
const char *s = string;
while (c = *s++)
请注意,assignment 拼写为 =
,而 ==
是相等性比较,这不是您的意思。
更高效的哈希版本:
unsigned int hash_function(const char* str)
{
unsigned int hash = 5381, c;
while(c = *str++)
hash += (hash << 5) + (c | 040);
return (hash % LISTS);
}