I am currently working on a hashtable program, but that isn't the problem, I have a insert function, but when I run it, the insert function only saves the most recent string read from the text.txt file, if the line is like "Finn 34" it has to insert Finn into the hash table with the value 34, if the hashed index already has something in it, it just reports a collision, however if it is the same String such as "Finn 98" it should report that Finn is already in that index. The problem is that every string points to the original name from the fscanf, I'm almost certain that the way to fix it is with malloc, but every-time I try to use it, it won't work.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TableSize 45
#define Max 50
///// dont forget the edit in main
typedef struct node {
char name[Max];
int value;
} node;
node array[Max];
void init_array(){
for (int i = 0; i < TableSize; i++){
//array[i] = NULL;
}
}
void insert(int index, node *p){
/*char * tempName = malloc (sizeof (char) * 50);
strcpy(tempName, p->name);*/
if (array[index].value != 0){
//if (array[index]->name == p->name){
if (strcmp(array[index].name, p->name) == 0){
printf("Error %s already exists at index %d\n\n", array[index].name, index);
}
else{
printf("Collision occured at index %d with\n\n", index);
}
}
else{
array[index] = *p;
strcpy(array[index].name, p->name);
printf("Stored %s with value of %d at index %d.\n\n", array[index].name, array[index].value, index);
}
}
int hash(char name[Max]){
int key = 0;
for (int i = 0; name[i] != '\0'; ++i){
char x = name[i];
key = key + x;
}
key = key % TableSize;
return key;
}
int main(int argc, char *argv[]) {
init_array();
FILE *fp;
char ch;
char name[Max];
int x, HaValue;
fp = fopen(argv[1], "r");
if (NULL == fp) {
//printf("file can't be opened \n");
fp = fopen("text.txt", "r"); ///////get rid of when done
}
node * p;
p = malloc(sizeof(struct node));
do{
x = 0;
int counter = 0;
if (fscanf(fp, "%49s", name) != 1) break;
if (fscanf(fp, "%d", &x) != 1) counter = 1;
HaValue = hash(name);
p->value = x;
strcpy(p->name, name);
if (counter != 0) {
}
else{
insert(HaValue, p);
}
} while(!feof(fp));
printf("%d %s %d", 12, array[12].name, array[12].value);
//test to see if the name was correctly saved. should be "12 Dog 12"
// Closing the file
fclose(fp);
return 0;
}
This is the text.txt document
Brom 89
Paul 25
Jake 34
Yokai 45
Jake
Dog 20
Paul 30
Brom
Kron 40
Finn 234