I am just learning c with the cs50 course and I just got introduced to pointers and data structures (It is very confusing please help). So I got a project where I need to make a hash table and I started first by trying to add some nodes to the zero index of the list instead of going for hash table right away and for some reason I am getting a segmentation fault while adding the node to the list. Its on line 31 (which is n->next = table[0]->next;) I am not able to understand why is this happening. Someone please help and thanks in advance
LoL I just forgot to add the code
Here It Is
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
typedef struct node
{
char *word;
struct node *next;
} node;
const unsigned int N = 10;
node *table[N];
for (int i = 0; i < 10; i++)
{
table[i] = NULL;
}
char *words[] = {"Hell", "Sup", "Brain", "Greek", "Mother", "Flip", "Poster", "Dark", "Apple", "Kandy"};
for (int i = 0; i < 10; i++)
{
char *wordle = words[i];
node *n = malloc(sizeof(node));
n->word = wordle;
n->next = table[0]->next;
table[0]->next = n;
printf("%s\n", table[0]->next->word);
}
}
>Solution :
You are initializing all table elements to NULL, and later you attempt to access the first (null) element: table[0]->next. This will result in dereferencing a null pointer, hence the segmentation fault you got.
What you need to do is allocating a node for each table entry:
for (int i = 0; i < N; i++) // You didn't make N constant for no reason, did you?
{
table[i] = malloc(sizeof(node));
}
Edit:
You can improve/optimise your code by avoiding repetitive calls to malloc() (as @Lundin suggested):
node* table = calloc(N, sizeof(node));