Thread: implementing a hashmap

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2024
    Posts
    23

    implementing a hashmap

    Hello,

    I want to implement a hashmap and get a segfault again when testing my program. It seems that I cannot access
    Code:
    test->hash
    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;
    }
    Last edited by john_12; 01-19-2024 at 11:51 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. implementing box zoom
    By mammaiap in forum Game Programming
    Replies: 1
    Last Post: 12-01-2010, 09:27 AM
  2. Hashmap of objects or references?
    By Noise in forum C++ Programming
    Replies: 6
    Last Post: 03-06-2009, 02:25 PM
  3. Implementing RLE
    By stevesmithx in forum C Programming
    Replies: 14
    Last Post: 04-03-2008, 02:03 PM
  4. Using an array with a hashmap
    By Reaem in forum C Programming
    Replies: 5
    Last Post: 03-18-2008, 03:49 PM
  5. Implementing CGI
    By peradox in forum Networking/Device Communication
    Replies: 4
    Last Post: 08-03-2005, 01:41 PM

Tags for this Thread