I am trying to convert a string into a unsigned char *. And i've been running in circles. My program prompts the user for a lastname which i take in as a string. I am then hashing the string into an integer using djb2. which takes an unsigned char * as a parameter. The goal of my program is to create a hash table using chaining to handle collisons.
unsigned long djb2(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
my code is as follows atm.
void insert(LinkedList<Person>* HashList1[], LinkedList<Person>* HashList2[], int listSize)
{
char * cstr;
string str;
cin >> str;
cstr = new char [str.size()+1];
strcpy (cstr, str.c_str());
int hashBucket1 = djb2(cstr) % listSize;
}
Im getting an error with the above telling me that "Argument of type "char *" is incompatible with parameter of type "unsigned char *" . Any help is greatly appreciated
When you have typing issues like this, it's a good indication that you are not using the language in the best way. Going back and forth between strings and char*s in C++ is a bad code smell .
Modify dbjc
to use a string:
unsigned long djb2(const string& str)
{
unsigned long hash = 5381;
for(string::iterator it=str.begin();it!=str.end();it++)
hash = ((hash << 5) + hash) + *it; /* hash * 33 + character */
return hash;
}
This will greatly simplify your insert:
void insert(LinkedList<Person>* HashList1[], LinkedList<Person>* HashList2[], int listSize){
string str;
cin >> str;
int hashBucket1;
hashBucket1 = djb2(str) % listSize;
}
The best solution is to modify dbjc
function, as suggested by @Steven Burnap.
If you cannot change dbjc
then cast cstr
to unsigned char *
in dbjc
call:
void insert(LinkedList<Person>* HashList1[], LinkedList<Person>* HashList2[], int listSize){
char * cstr;
string str;
cin >> str;
cstr = new char [str.size()+1];
strcpy (cstr, str.c_str());
int hashBucket1;
hashBucket1 = djb2((unsigned char *)cstr) % listSize; // <-- here is the change
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.