Hello,
I want to implement a hashmap and get a segfault again when testing my program. It seems that I cannot access as it throws the segmentation fault error. I suspect that I should use
Code:
Entry* test = (Entry*) malloc(sizeof(Entry));
instead. Why does it not work without malloc()?
Code:
#include <stdio.h>
#define TABLE_SIZE 16
typedef int Data;
typedef struct entry Entry;
struct entry {
Data value;
unsigned int hash;
Entry* next;
};
void insert_into(Entry* table[], Data data){
Entry entry = {data, 0, NULL};
entry.hash = ((unsigned int) &entry) % TABLE_SIZE;
if (table[entry.hash] == NULL){
table[entry.hash] = &entry;
}
}
int main(){
Entry* test = {1,0,NULL};
printf("%p\n", test);
test->hash = (unsigned int) test;
printf("%d\n", test->hash);
Data data_points[5] = {3,5,2,12,9};
Entry* lookup_table[TABLE_SIZE];
for (int i = 0; i < 5; i++){
insert_into(lookup_table, data_points[i]);
}
for (int i = 0; i < TABLE_SIZE; i++)
printf("%i = %s\n", i, lookup_table[i]->value);
return 0;
}