r/C_Programming • • Aug 08 '26

Hash table

I am newbie and a beginner in c language. I would like to learn the hash table for my next semester.

I kindly ask for some help in this matter. I still struggle in the basics even using the ai models.

8 Upvotes

29 comments sorted by

View all comments

Show parent comment

1

u/TheChief275 Aug 10 '26

Yes there is; you can use the same shifting approach that is often used to avoid tombstones, but for priority purposes instead. But the main point was that I wouldn't suggest your hash table variant to someone who wants to implement their first hash table. Open addressing is way more suited to that, as it's essentially just a fancy array on the data structure side

1

u/flatfinger Aug 10 '26

Code to search for an item and add it if it doesn't exist would be something like:

first_loc = hashTable->indices[hashvalue & hashTable->hashMask];
if ((item_loc >= hashTable->liveItems) ||
   (((hashes[item_loc] ^ hashValue) & hashTable->hashMask) != 0))
  first_loc = UINT_MAX;
item_loc = first_loc;
// Search through buckets
do
{
  if (item_loc -> hashTable->liveItems)
  {
    item_loc = hashTable->liveItems;
    hashTable->liveItems++;
    hashTable->next[item_loc] = first_loc;
    hashTable->indices[hashValue & hashTable->hashMask] = item_loc;
    hashTable->hashes[item_loc] = hashvalue;
    hashTable->items[item_loc] = passed_item;
    break;
  }
  else if (hashTable->hashes[item_loc] == hashvalue &&
      items_equal(&hashTable->items[item_loc], &passed_item)
    break;
  item_loc = hashtTable->next[item_loc];
} while(1);

Decreasing hashTable->live_items will remove items from the table without any need to do anything with the contents of the arrays. When a new items is added, it may receive a slot that was associated with a different masked hash value, but that will be detected because the hash value associated with the slot won't be appropriate for the masked hash value.

1

u/TheChief275 Aug 11 '26

Dumping some code != an explanation