2017-03-18 6 views
1

変換された数値をハッシュ関数のキー値として使用するには、char * typeの文字列を長整数に変換しようとしていました。私はatolとstrtolの両方の関数を試してみましたが、私は別の文字列で関数を呼び出すたびに同じハッシュ値を返します。以下は私のハッシュ関数です。stringから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 

フルキー番号iが引数として渡すのchar *キーによると、変換された整数は、だけでなく、同じまま変化していてもハッシュ値 私はどんな助けにも感謝します...事前に感謝します。

答えて

1

これは、3575472318696がintまたはlong(私の実装では32ビットとみなされます)に収まらないからです。

それはそれは、その場合には最大long値を返すように、2^31になります - 1 = 2147483647

+0

はどうもありがとう、それはproblem.Iが長いlong int型と使用さんご礁にタイプを変更しましたatolの代わりに、それは完全に動作します! –

+2

@LoriKougioumtzian strtoll()は、入力値が大きすぎてlong long *に収まらないことを呼び出し元に伝える方法があるため、これを行うためのより良い方法です。 – Jens

+1

[なぜ私はatoi()を使用すべきではありません](http://stackoverflow.com/q/17710018/995714)? [有害だと思われる](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/) –

関連する問題