I have a struct defined in C as follows
typedef struct {
unsigned int size;
unsigned int pool_size;
route _routes[SIZE_OF_FLEET];
request _request_pool[SIZE_OF_PROBLEM];
/* stores which request is contained in which route */
unsigned int _request_map[SIZE_OF_PROBLEM];
} solution;
I am trying to define a hash function for this struct as follows
unsigned long long solution_hash(solution const *_sol)
{
unsigned long long hash = 0;
unsigned short c;
unsigned short *reinterpret_sol;
reinterpret_sol = (unsigned short*)&_sol;
size_t size_ = sizeof(solution);
size_t elem_size_ = sizeof(unsigned short);
int len = (int)size_/elem_size_;
for (int i = 0; i < len; i++) {
c = reinterpret_sol[i];
hash += c;
}
return hash;
}
The problem is everytime I make a call to solution_hash function, the hash value of the same solution changes. Successive calls increment the value by 32 for the same solution.
What is wrong with this code? Is there a better way to implement a hash function for a struct?