'Questions for building a HashMap in C
I've encountered problems when I'm trying to build a hashMap using C. My goal is to build a hashMap with an array of linkedlist appended.
I'm now working on the insert element function, and here is the strange part. I hope to insert a newNode at the beginning. When I use a temp node head to store the "head" of this linkedlist and try to insert, it fails with no value insert. But if I change the head directly to "_hashmap->arrayOfLists[bucket]", then it works.. I do not know why and I think having a temp node should work.. Anyone can help with this? Thanks!
typedef struct pair{ char* key; char* value; }pair_t;
typedef struct node{ struct node* next; pair_t* kv;}node_t;
[Original problematic code]
void hashmap_insert (hashmap_t* _hashmap, char* key, char* value){
pair_t* newPair = (pair_t*)malloc(sizeof(pair_t)); newPair->key = (char*)malloc(strlen(key) * sizeof(char)+1); newPair->value = (char*)malloc(strlen(value) * sizeof(char)+1); strcpy(newPair->key, key); //copy the input key into the malloc space. strcpy(newPair->value, value); //copy the input value into the malloc space. //create a newNode that is to be inserted. node_t* newNode = (node_t*)malloc(sizeof(node_t)); newNode->kv = newPair; newNode->next = NULL; unsigned int bucket = _hashmap->hashFunction(key, _hashmap->buckets); node_t* head = _hashmap->arrayOfLists[bucket]; // if the bucket is empty if(head == NULL) { head = newNode; } else {//insert the newNode at the front. newNode->next = head; head = newNode; }}
【The code that works]
if(_hashmap->arrayOfLists[bucket] == NULL) { _hashmap->arrayOfLists[bucket] = newNode; } else { newNode->next = _hashmap->arrayOfLists[bucket]; _hashmap->arrayOfLists[bucket] = newNode; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
