hi im vinzent
hi im vinzent

Reputation: 163

Linked List in Hash Table (with struct)

I'm implementing a hash table with pointers to struct instances.

Struct:

typedef struct student 
{
    int matrikelnummer;
    char *name;
    struct student *next;
} student;

Array (with pointers on my struct):

student *hash_table[SIZE];
...
for (int i = 0; i < SIZE; i++)
    hash_table[i] = NULL;

I'm creating a instance of my struct with proper memory management:

char *name = malloc(100);
student *temp = malloc(sizeof(student));
if (temp == NULL || name == NULL)
    return;

printf("Neuer Student hinzufuegen:\n");
printf("Name: ");
scanf("%99s", name);
temp->name = malloc(strlen(name) + 1);
if (temp->name == NULL)
    return;
strcpy(temp->name, name);
free(name);
name = NULL;

printf("Matrikelnumer: ");
scanf("%d", &temp->matrikelnummer);

temp->next = NULL;

Until here it is working properly, if I check my temp (instance of struct) while debugging the program it looks fine. At the end of this function changing the pointer in hash_table[0] to my temp instance seems to work:

hash_table[0] = &temp;
/* hash_table[get_hash_key(temp->matrikelnummer)] = &temp; */

My program crashes after I try to print the members of my hash_table afterwards like following:

printf("matrikelnumer: %d\n", hash_table[0]->matrikelnummer);

Output: matrikelnummer: 9741328 (it looks like the address itself printed with %d)

and it crashes after trying to print the name with following code line:

printf("name: %s\n", hash_table[0]->name);

Do I access the variables wrong? I tried already several ways to access the members, but its mostly crashing or doing something I'm not able to follow.

Any hints and help appreciated, also when it comes to coding style etc.

Upvotes: 1

Views: 761

Answers (1)

nikartix
nikartix

Reputation: 717

Bug is on line:

hash_table[0] = &temp;

temp is pointer already, so you are assigning struct student** to struct student* array element, which causes all remaining errors.

Change to:

hash_table[0] = temp;

Upvotes: 3

Related Questions