1

I tried adding functionality to the djb2 hash function, but it doesn't appear to like the changes. Specifically, I'm trying to include a loop that converts words (strings) to lower case. It throws the following two errors:

  1. Incompatible integer to pointer conversion assigning to char * from int
  2. Cannot increment value of type char *[45]

Note that in the original code *str++ appeared in the while loop. This is my first hash table, and I'm rather shaky on pointers. Any insight on where I've gone wrong would be appreciated.

// 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] != '\0'; i++)
    {
        string[i] = (tolower(str[i]));
    }

    while (c == *string++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return (hash % LISTS);
}

2 Answers 2

1

More efficient version of your hash:

unsigned int hash_function(const char* str)
{
    unsigned int hash = 5381, c;
    while(c = *str++) 
      hash += (hash << 5) + (c | 040);

    return (hash % LISTS);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Much appreciated! I assume this is a reformulation of the original and does not convert all to lower case? Out of curiosity, what does (c | 040) mean/do, exactly. The combination of a character and a bitwise OR seems unusual. I have only recently begun doing work at the bit level, which is both cool and a total mind@#$&%.
(x|040) turns "x" to lowercase, and not change numbers. However, it changes some CTRL-symbols to some printable ones. However, this is not important for hashing purposes.
1

This:

char* string[45];

means "array of 45 character pointers", you should drop the asterisk.

And you can't iterate over an array by incrementing the variable, the array variable cannot be changed. You can use a separate pointer:

const char *s = string;
while (c = *s++)

Note that assignment is spelled =, while == is comparison for equality which is not what you mean.

1 Comment

Many thanks for the reply & clarification! I'll give it a shot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.