Hello everybody:
I am doing a lab for school and need major help. I am trying to read in names and phonenumbers from a text file, and put this information into a hash table. I am using lastnames for the key values. The Insert function, which inserts records(structs) into the hash table uses open addressing with linear probing. The hash table itself is simply an array of structs. The frustrating thing is that the code I have below works perfectly if I enter string literals, but when I pull in the information from a file it isn't stored properly in the table. It only seems to store the last entry read from the file. Also whe I try to print the table using the PrintTable function I created for testing purposes I get segmentation faults
Thanks...
Tim.
Code:
#define HASHSIZE 53
typedef char *Key;
typedef struct item{
Key key;
char *number;
}Entry;
typedef Entry HashTable[HASHSIZE];
main()
{
char *name, *phone, *inputString;
FILE *fp;
Entry newEntry;
HashTable H;
CreateTable(H);
inputString = (char *)malloc(50*sizeof(char));
if((fp = fopen("phone.txt", "r")) != NULL)
{
while(!feof(fp))
{
fgets(inputString, 50, fp);
name = (char *)strtok(inputString, "; ");
phone = (char *)strtok(NULL, ";");
newEntry.key = name;
newEntry.number = phone;
Insert(H, newEntry);
}
}
else
printf("Error in opening file.\n");
PrintTable(H);
}
int Hash(Key s)
{
unsigned h = 0;
while(*s)
h+=*s++;
return h%HASHSIZE;
}
void CreateTable(HashTable H)
{
int i;
for(i=0; i<HASHSIZE; i++)
H[i].key = NULL;
}
void Insert(HashTable H, Entry newitem)
{
int pc = 0;
int increment = 1;
int probe = 0;
probe = Hash(newitem.key);
while(H[probe].key != NULL && strcmp(newitem.key, H[probe].key) && pc <= HASHSIZE)
{
pc++;
probe = (probe + increment)%HASHSIZE;
increment++;
}
if(H[probe].key == NULL)
H[probe] = newitem;
else if (strcmp(newitem.key, H[probe].key) == 0)
printf("Same key cannot appear twice in the hash table.\n");
else
printf("Hash table is full.\n");
}
void PrintTable(HashTable H)
{
int i;
for(i=0; i<HASHSIZE; i++)
{
if(H[i].key)
printf("At index: %d Key: %s value: %s\n", i, H[i].key, H[i].number);
}
}