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

0

u/[deleted] Aug 08 '26

[deleted] — view deleted comment

4

u/thank_burdell Aug 08 '26

Yup. Array of pointers to linked lists, and a hashing function, and voila, you have a hashtable.

0

u/[deleted] Aug 08 '26

[deleted] — view deleted comment

7

u/Puzzleheaded_Study17 Aug 08 '26

It wouldn't work well since you won't have fast access time. In order to get the expected performance from a hash table you need to be able to access a random list in constant time (ignoring hashing time and collisions).

3

u/thank_burdell Aug 08 '26

You’d lose the lookup performance increase that’s the whole point of hashtables, but technically you could. There’s just not a good reason for it.

0

u/[deleted] Aug 08 '26

[deleted] — view deleted comment

3

u/thank_burdell Aug 08 '26

There are multiple ways to determine when you need to rehash, but as for how, your rehash should double the size of the array, make twice as many linked lists for it, and then iterate across the original to migrate them to the new. It’s an expensive operation so you don’t want to do it too often, and trying to guess the “right” size for your hashtable is a matter of testing your performance at various levels.

As for the function, it remains unchanged, you just look at one more bit from the hash it generates.

2

u/chrism239 Aug 08 '26

" A linked list is essentially an array, containing a bunch of linked lists."

Ouch!

1

u/TheChief275 Aug 08 '26

Like what do they even mean by that? Are they trying to describe a linked list in what it roughly represents? Yes, it could be used in the same situations as an array but that sure as hell isn't a good idea, and it sure as hell doesn't make it an array

4

u/chrism239 Aug 08 '26

Maybe they meant “A hash table is essentially….”

1

u/TheChief275 Aug 08 '26

Oh that must be it! Couldn't have figure that out myself

0

u/[deleted] Aug 08 '26

[deleted] — view deleted comment

2

u/TheChief275 Aug 08 '26

Just use the term list; beginners probably know it from Python or C#. Then describe how actually, that list is more like an array while a classical list is just a straight 1-dimensional tree, with each node being the parent of the next.

Simple enough

1

u/TheChief275 Aug 08 '26

I like open addressing more, and it is way simpler for a beginner to understand. Linked list buckets are really likely to devolve into a linear search, and even then you're losing out on a lot of iteration speed for cache locality. Only way to counteract that would be to use a single contiguous buffer to allocate your separate nodes in, but I highly doubt OP will work up such a solution