1

I've been trying to convert a char* type c string to a long integer in order to use the converted number as a key value to a hash function. I tried both atol and strtol functions, and both return to me the same hash value everytime I call the function with a different string.The following is my hash function.

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;
}

And this is the output I get:

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

Even though the full key number changes according to the char* key i pass as an argument, the converted integer stays the same as well as the hash value. I would appreciate any sort of help...thanks in advance.

1 Answers1

1

That's because 3575472318696 does not fit in an int or long (which I assume are 32 bits on your implementation).

It looks like it returns the maximum long value in that case, 2^31 - 1 = 2147483647.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you so much,that was the problem.I changed the type to a long long int and used atoll instead of atol and it works perfectly! – Lori Kougioumtzian Mar 18 '17 at 16:44
  • 2
    @LoriKougioumtzian Note that strtoll() is a better way to do this as it has a way to tell the caller *the input value was too big to fit into a long long*. – Jens Mar 18 '17 at 16:47
  • 1
    [Why shouldn't I use atoi()](http://stackoverflow.com/q/17710018/995714)? Because [it's considered harmful](https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/) – phuclv Mar 18 '17 at 16:50