Hash functions

So in my C++ book, it teaches how to create a simple hash function for use with a basic hash map container. But I dont understand one line of the code:

 
  unsigned char b = *((unsigned char*)&key + i);


Where 'key' is a templatized variable 'const T& key'. What exactly is this line doing?? And also, what is an 'unsigned char'? I know about unsigned integers, but char's?
unsigned char is an integer type that has the size of a byte.

&key gives you a pointer to the key value. The type of the pointer is T* (pointer to T).

(unsigned char*)&key casts the pointer to an unsigned char* (pointer to unsigned char). This will allow you read the bytes in the key value.

(unsigned char*)&key + i moves the pointer i positions forward. If i is 0 it will give you a pointer to the first byte, if i is 1 it gives you a pointer to the second byte, and so on.

*((unsigned char*)&key + i) dereferences the pointer, which means you read what the pointer points to.

So to summarize this line of code: It reads the i:th byte in the key and stores it in b.
Last edited on
For extra fun, it could also have been written i[(unsigned char*)&key].
Topic archived. No new replies allowed.