Bob Winchester
Bob Winchester

Reputation: 13

C Hash Table Problem, Everything has same value

For some reason when I insert elements into my hash table all elements at the same index end up having the same value. For example if I have three elements at index 2 of the hash table then all three would have the same "word" as the last one inserted into that index. I dynamically allocate the memory for each element before inserting, so I don't know the issue.

Anyone have a clue? Thanks.

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


struct word *hashTable[20];

void func(const char *file)
{
     char word[1000];
     int i;

     FILE *infile = stdin;
     infile = fopen(file, "rb");    
     if(infile == NULL) {
        printf("cannot open [%s]\n", file);
        return;
     }

     while(fscanf(infile, "%s" word) != EOF) {      

        struct word *w;

           w = malloc( sizeof( struct word ));
           w->word = word;           
           w->next = NULL;
           insert(w);
     }

     fclose (infile);
}

void insert(struct word *v)
{     
  if( hashTable[hash(v->word)] )
  { 
    struct word *end = hashTable[hash(v->word)];

    while(end->next != NULL ) {
      end = end->next;
    }
    end->next = v;
  }
  else
    hashTable[hash(v->word)] = v; 
}

Upvotes: 1

Views: 760

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126243

That's because you set the word pointer of every struct word to point at the same word array (the one defined as a local variable in func). This array gets overwritten with each word from the file, so they'll all end up being the same. You need to allocate more space for each word array you want to keep, and copy it there. The strdup function will do that nicely for you if you change it to be

w->word = strdup(word);

Upvotes: 3

Related Questions