I want to calculate a hash of the structure passing as string. Although vlanId values are different, the hash value is still the same. The StringHash() funtion calculates the values of the hash. I haven't assigned any value to portId and vsi.
#include<stdio.h>
#include <functional>
#include <cstring>
using namespace std;
unsigned long StringHash(unsigned char *Arr)
{
hash<string> str_hash;
string Str((const char *)Arr);
unsigned long str_hash_value = str_hash(Str);
printf("Hash=%lu\n", str_hash_value);
return str_hash_value;
}
typedef struct
{
unsigned char portId;
unsigned short vlanId;
unsigned short vsi;
}VlanConfig;
int main()
{
VlanConfig v1;
memset(&v1,0,sizeof(VlanConfig));
unsigned char *index = (unsigned char *)&v1 + sizeof(unsigned char);
v1.vlanId = 10;
StringHash(index);
StringHash((unsigned char *)&v1);
v1.vlanId = 12;
StringHash(index);
StringHash((unsigned char *)&v1);
return 0;
}
Output:
Hash=6142509188972423790
Hash=6142509188972423790
Hash=6142509188972423790
Hash=6142509188972423790
string Str((const char *)Arr);, and an inspection window will tell you very quickly that this isn't the right way to hashVlanConfig. And not that it is necessarily related, " I haven't assigned any value to portId and vsi" - um. yes you did. what do you think thatmemsetdid?StringHash((unsigned char*)&v1): you cast&v1to a(unsigned char*)but&v1is not a pointer to a string, it's a pointer toVlanConfig. The cast won't magically transform yourstructinto a string. It will just pretend&vipoints to a string, but it doesn't. If you use casts in C++, you're doing solmething most of the timestring Str((const char *)Arr);But you are building this like it is a C-String which is terminated by\0. I assume the first bye is zero and thus you are hashing an empty string. Build the string like this:string Str((const char *)Arr, <Size of Object being hasshed>);Note: I only recomend this to show why it is happening. You should do it properly as shown by @nvoigt below.