PTN
PTN

Reputation: 1692

Hash table containing linked lists of words C

I am totally new to C so I am having troubles with hash table and linked list. Below is the code I have:

typedef struct WordList {
   char *word;
   struct WordList *next;
} WordList;

typedef struct HashTable {
   int key;
   struct WordList value;
} HashTable;

#define TABLE_SIZE 10

HashTable *table[TABLE_SIZE] = { NULL };

//Insert element
void insertElement(int key, char *word) {
   int i = 0;

   // check if key has already existed
   while((table[i]->key != 0) && (i < TABLE_SIZE)) {
      if(table[i]->key == key) { // if find key    
         struct WordList wl = table[i]->value;
         // assign word to temp list then append to existed list
         struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
         temp->word = word;
         temp->next = wl;
         wl = temp;
         table[i]->value = wl; // add  word to existed linked list

         return; // exit function and skip the rest
      }

      i++; // increment loop index 
   }

   // find a NULL slot and store key and value
   if(table[i]->key == NULL) {
      table[i]->key = key;

      struct WordList wl = table[i]->value;
      // assign word to temp list then append to existed list
      struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
      temp->word = word;
      temp->next = wl;
      wl = temp;
      table[i]->value == wl;
   }
}

int main() {
   // test call
   insertElement(1, "blah\0"); 

   int i;

   for ( i=0; i < 10; i++)
   {
      printf("%d: ", i);

      struct HashTable *tableTemp = table[i];

      while (entryTemp != NULL)
      {
         printf("(%d)\n", tableTemp->key);
         tableTemp = tableTemp->next;
      }

      printf("\n");
   }

   return 0;
}

I am getting this error:

In function ‘insertElement’:
error: invalid initializer
struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));
                                                                   ^

Can you tell me which part did I mess up? I know the coding style here is horrible too but can you fix the actual problem first then comment on the rest later please?

Upvotes: 0

Views: 816

Answers (1)

Jim Lewis
Jim Lewis

Reputation: 45045

struct WordList temp = (struct WordList *)malloc(sizeof(struct WordList));

Notice that the left hand side is a structure, but the right hand side is a pointer. You probably want:

struct WordList *temp = (struct WordList *)malloc(sizeof(struct WordList));

Upvotes: 4

Related Questions