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/) –