here is my hash table code that reads in a file and puts it into a hash table and handles collisions with a linked list approach.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct List { char *word; struct List *next; } List;
#define HASHSIZE 65536
#define LEN 50
static struct List *hashtab[HASHSIZE];
static FILE *open_file (char *file, char *mode)
{
FILE *fp = fopen (file, mode);
if (fp == NULL){
perror ("Unable to open file");
exit (EXIT_FAILURE);
}
return fp;
}
List *list_alloc (void)
{
List *tmp = calloc (1, sizeof (List));
if (tmp == NULL){
fprintf (stderr, "Error: calloc ()\n");
}
tmp -> word = NULL;
tmp -> next = NULL;
return tmp;
}
int is_punctuation (int a)
{
return a == ' ' || a == '\n' ||
a == EOF || a == ',' ||
a ==';' || a =='.'||
a =='!' || a =='?' ||
a ==':' || a =='`';
}
unsigned rot_hash (void *key)
{
unsigned char *p = key;
unsigned h = 0;
int i;
for (i = 0; i < strlen(key); i++)
h = (h << 4) ^ (h >> 28) ^ p[i];
return h % HASHSIZE;
}
void install (char *s)
{
List *tmp = NULL;
unsigned int h = rot_hash (s);
if (hashtab[h] -> word == NULL){
hashtab[h] = list_alloc ();
strcpy (hashtab[h] -> word, s);
printf ("Put value into empty space\n");
}else{
for (tmp = hashtab[h]; tmp != NULL; tmp = tmp -> next){
if (tmp -> next == NULL){
tmp -> next = list_alloc ();
strcpy (tmp -> next -> word, s);
printf ("Put value into a linked list\n");
break;
}
}
}
}
int main (int argc, char *argv[])
{
int x;
char a, word[LEN];
x = 0;
FILE *fp = open_file (argv[1], "r");
do{
a = fgetc (fp);
if (is_punctuation(a)){
if (x != 0){
word[x] = '\0';
install (word);
x = 0;
}
}else{
word[x] = tolower(a);
x++;
}
} while (a != EOF);
fclose (fp);
return 0;
}
for some reason i keep getting a bus error and a warning that says the file is not of required architecture but i don't see any mistakes in the code. where am i going wrong?
thanks