I am trying to develop a hash table in the C Programming Language which always fails with seg fault. I am trying to do seperate chaining so I created a struct which has two properties: word and next. The word is a char* and next a pointer to the next node, eventually creating a hash table that conatains an array of linked list.
typedef struct node
{
char* word;
struct node* next;
}node;
node* table[26];
After this I am indexing into the table by using a hashing function which simply indexes into the table.
Do you have a fix?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>
typedef struct node
{
char* word;
struct node* next;
}node;
node* table[26];
int hash(char* key);
void index();
int main(int argc, char* argv[])
{
index();
return 0;
}
int hash(char* key)
{
int hash = toupper(key[0]) - 'A';
int res = hash % 26;
return res;
}
void index()
{
printf("Insert a word: ");
char* k = GetString();
node* predptr = malloc(sizeof(node));
node* newptr = malloc(sizeof(node));
for(int i = 0; i < 26; i++)
{
if(hash(k) == i)
{
predptr = table[0];
predptr->next = newptr;
newptr = predptr;
break;
}
else
{
}
}
}
table
is an array of 26 pointers, all initialized toNULL
.Specifically
table[0]
is aNULL
pointer and you try to dereference it