r/C_Programming • • 27d ago

Question Need some openions on my first hashTabel

be brutal

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
enum Type{Int,Float,Char};


typedef struct Node
{   
    void *Value;
    struct Node *Next;


    char Key[20];
    enum Type type;
}Node;
typedef struct 
{
    Node **Nodes;
    size_t Size;
    size_t TotalElements;
    size_t Cap;
}Tabel;
Tabel *CreatTabel(){
    Tabel *tb=malloc(sizeof(Tabel));
    tb->Cap=16;
    tb->TotalElements=0;
    tb->Nodes = malloc(tb->Cap* sizeof(Node*));
    tb->Size=0;
    return tb;
}


size_t hash(char *str)
{
    size_t hash = 5381;
    int c;
    while ((c = (unsigned char)*str++))
        hash = ((hash << 5) + hash) + c;
    return hash;
}


void *CreatNode(char key[],void* value,enum Type tp,size_t size){
    Node *nd =calloc(1,sizeof(Node));
    memcpy(nd->Key, key, strlen(key)+1);
    nd->type=tp;
    nd->Value=malloc(size);
    
    memcpy(nd->Value, value, size);
    return nd;
}
void *TabelGet(Tabel* tb,char key[],enum Type tp){
    size_t idx=hash(key)%tb->Cap;
    Node *nd=tb->Nodes[idx];
    Node *r=NULL;



    while (nd && nd->Next!=NULL && r==NULL)
    {
         
        if (strcmp(nd->Key,key)==0){


            r=nd;
        }


        nd=nd->Next;
    }


    if (r==NULL && strcmp(nd->Key,key)==0){
            r=nd;
    }
    if (r->type==tp){return r->Value;}


    return NULL;
}
bool TabelSet(Tabel* tb,char key[],void* value,enum Type tp,size_t Size){
    if (tb->Size+1==tb->Cap){
        Node **tmpArray=malloc(sizeof(Node*)*tb->TotalElements);
        size_t num =0;
        for (size_t i = 0; i < tb->Cap; i++)
        {
            while (tb->Nodes[i])
            {
                tmpArray[num]=tb->Nodes[i];
                tb->Nodes[i]=tb->Nodes[i]->Next;
                num++;
            }
            
        }
        
        tb->Cap+=tb->Cap;
        free(tb->Nodes);
        tb->Nodes=malloc(sizeof(Node)*tb->Cap);
        tb->Size=0;
        Node *tmpNode=NULL;
        for (size_t i = 0; i < tb->TotalElements; i++)
        {
            size_t idx2=hash(tmpArray[i]->Key)%tb->Cap;
            if (tb->Nodes[idx2]){tmpNode=tb->Nodes[idx2];}
            else{tmpNode=tmpArray[i];}
            while (tmpNode->Next){
              
                    tmpNode=tmpNode->Next;
            }
            tmpNode->Next=tmpArray[i];
            
        }
        
    }
    size_t idx=hash(key)%tb->Cap;
    if (tb->Nodes[idx]){
        Node *tmp=tb->Nodes[idx];
        do
        {
            if (strcmp(tmp->Key,key)==0){
                free(tmp->Value);
                tmp->Value=malloc(sizeof(void)*Size);
                memcpy(tmp->Value,value,Size);
                tmp->type=tp;
                
                tb->TotalElements++;
                return true;
            }


            if (tmp->Next==NULL)break;
            tmp=tmp->Next;
        }while (tmp && tmp->Next!=NULL);
        tmp->Next=CreatNode(key,value,tp,Size);
        
        tb->TotalElements++;
        return true;
    }
    else{
        tb->Nodes[idx]=CreatNode(key,value,tp,Size);
        tb->Size++;
    }
    return false;
}
void FreeNode(Node *nd){
    Node *tmp=nd->Next;
    while (nd)
    {


        tmp=nd->Next;
        if (nd->Value!=NULL) free(nd->Value);
        free(nd);
        nd=tmp;
    }
    
    
}
void FreeTabel(Tabel *tb){
    for (size_t a=0; a<tb->Size;a++){
        if (tb->Nodes[a]!=NULL){FreeNode(tb->Nodes[a]);}


    }
    free(tb->Nodes);
    free(tb);
}


int main()
{
    Tabel *tb= CreatTabel();



    
    size_t num = 32;
    char str[20]; // Ensure buffer is large enough (at least 12 bytes for a 32-bit int)
    for (size_t i = 0; i < num; i++)
    {   
        snprintf(str, sizeof(str), "%ld", i);
        char c=(i+64);
        TabelSet(tb,str,&c,Char,sizeof(int));
    }
    
    for (size_t i = 1; i < num; i++)
    {
        snprintf(str, sizeof(str), "%ld", i);
        char *p=(char*)TabelGet(tb,str,Char);
        printf("%c\n",*p);
    }
    
    
    FreeTabel(tb);
    return 0;
}
0 Upvotes

22 comments sorted by

11

u/onlyonequickquestion 27d ago

You spelled "table" wrong

10

u/FirmAndSquishyTomato 27d ago

It's French. It is a fancy pronunciation.
It's a classy type of hash table for the upper class.

8

u/clickyclicky456 27d ago

It's only a hash tabel if it's from the Tabell region of France. Otherwise it's just sparkling lookup.

6

u/onlyonequickquestion 27d ago

Ahhhh Oui oui, l'hash tabel. Je m'excuse. 

2

u/jevin_dev 27d ago

never said i was able to write well

4

u/Skibidibob4 26d ago

Minor spelling mistake 

1

u/[deleted] 26d ago

Nice but imo, you can make

```
#define CAP 16

typedef struct
{
Node *Nodes[CAP];
size_t Size;
size_t TotalElements;
}Tabel;

```

Its more easier

2

u/mikeblas 26d ago

Please correctly format your code.

0

u/pjl1967 27d ago edited 27d ago

It's a common mistake to incorporate the keys and/or values directly into the table or entries (common because languages with templates or generics do, so people try to do that in C as well); but in C, it doesn't work well. Your table also:

  • Doesn't allow the user to supply their own hash or comparison functions.
  • Doesn't set the number of buckets equal to a prime number.

A better hash table is here and here.

4

u/ffd9k 27d ago

Doesn't set the number of buckets equal to a prime number.

Instead of prime numbers, it's actually more common to use powers of two, because this allows you to use bitwise-and instead of modulo to find the bucket.

-2

u/pjl1967 27d ago

Powers is two is something you don't want because it renders the lower bits useless. See here among other places.

5

u/ffd9k 27d ago

Powers of two are fine if you either use a reasonably good hash function with enough randomness across all bits, or use some avalanche function or Fibonacci hashing to improve the result afterwards. This is usually still cheaper than modulo.

1

u/pjl1967 27d ago

But if you allow the user to specify his own hash function (as you might if you're writing a generic hash table container), you can't guarantee a good-enough hash function. Using primes not near powers of 2 is an insurance policy against that.

There are always trade-offs.

2

u/21Ali-ANinja69 26d ago

For one of my university CS projects, we wrote a compiler and had to implement a hash table as the symbol tables's underlying representation. We just stored the offsets between each power of 2 and the largest prime less than it. So you can just do (2 << table->idx) - offsets[table->idx] to get the size of the table when resizing. Off course this means there is a limit to its resizing, but its a toy compiler targeting the JVM, so it was fine. Also Java apparently does powers of two for HashSet<>, but uses red-black trees instead of linked lists for collisions.

1

u/jevin_dev 26d ago

im honestly impressed and scared of how little I know about programming

1

u/21Ali-ANinja69 26d ago

We got quite a bit of skeleton code, but yes even with my degree right around the corner, I consider it my crowning achievement.

1

u/jevin_dev 26d ago

honestly i just want to make libs for python with c the language its cool as hell but the more complex the project starts to become the more i want to just start from scratch since i think of new ways to go around c limits

0

u/pjl1967 26d ago

I personally wouldn't use Java as a good example of anything.

Ideally, you want collisions to be non-existent to infrequent which means the length of the linked lists is very small.

Using red-black trees sounds like compensation for a bad hash function because there would be enough collisions that you want to make searching the set of entries that all hash to the same bucket faster.

The better solution is to use a better hash function, a prime number of buckets, and avoid powers of two.

If the number of collisions is small so the linked lists are short, then linked lists are good enough.

1

u/xeow 25d ago edited 25d ago

A good hash table uses the upper bits of the hash, not the lower bits of the hash. It's literally just one machine instruction to take the hash and convert into an index. You multiply the hash value by the capacity and take the upper word of the result and throw away the lower word of the result. Works equally well, and equally fast, for any hash modulus.

There's no sensible reason to use a prime number for the hash modulus, and there never was. That's 1970s–1980s thinking, before fast universal hash functions were discovered.

1

u/pjl1967 25d ago

I addressed this in my other comment.

-2

u/Reasonable_Return151 27d ago

I just skimmed but personally I wouldn’t use any dynamic allocation inside a hash table. It kind of defeats the speed benefit because you will spend more cycles allocating and freeing.

Plus that means you have to worry about freeing.

Just make it huge and and don’t let it overflow by setting good boundaries. Is my personal take.

You will feel the difference in speed and determinism. When using it in large projects.

1

u/jevin_dev 26d ago

i do agree with you it be better to ues an *Nodes and creat them before not **Nodes i just took the easy way out