1
我一直试图将char *类型的c字符串转换为长整数,以便将转换后的数字用作哈希函数的键值。我尝试了atol和strtol函数,并且每次使用不同的字符串调用函数时都返回相同的散列值。以下是我的散列函数。从字符串到long int的转换为不同的字符串返回相同的值
int h_function(char* key,h_table* table){
int i;
char* key_i=key;
char str[14];
char code[4];
char number[11];
long result;
//printf("%c\n",key_i[13]);
//there is a "-" in key[3] so i want to remove that first
for(i=0;i<3;i++){
code[i]=key_i[i];
}
code[3]='\0';
printf("This is the code: %s\n",code);
for(i=0;i<10;i++){
number[i]=key_i[i+4];
}
number[10]='\0';
printf("This is the number: %s\n",number);
strcpy(str,code);
strcat(str,number);
printf("This is the full key number: %s\n",str);
//converting to long int
result=atol(str);
printf("This is the key converted to an integer: %ld\n",result);
int hash_value=(result % table->size);
printf("The hashvalue is: %d\n",hash_value);
return hash_value;
}
这是输出我得到:
This is the code: 357
This is the number: 5472318696
This is the full key number: 3575472318696
This is the key converted to an integer: 2147483647
The hashvalue is: 22
This is the hashed index: 22
即使全键数量变化根据的char *键我作为参数传递,转换成的整数保持不变,以及散列值。 我会很感激任何形式的帮助......提前致谢。
太感谢你了,那是疑难问题改变了类型为long long int和使用环礁而不是atol,它完美的工作! –
@LoriKougioumtzian请注意,strtoll()是一个更好的方法,因为它有一种方法可以告诉调用者*输入值太大而不适合长时间的*。 – Jens
[为什么不应该使用atoi()](http://stackoverflow.com/q/17710018/995714)?因为[它被认为是有害的](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/) –