For past 2 days I am not able to complete this code. I am trying to implement a hashtable. It contains only a single struct pointer variable start
which stores a single struct object. I have declared an array of 26 objects of Hashtable
to store a structure. The structure is stored by identifying the starting letter of val
, which is a struct member.
If val="ascii"
then it stores it in ht[0]
. If val="struct"
, then it stores in ht[18]
.
I am inserting 5 values. If the values are already present in the hashtable, then it prints the value from the hashtable. Otherwise, it inserts the value. My program works fine without reallocation. When reallocation occurs the value in the hashtable does not show up. See the output below the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct List {
char val[20];
};
struct Hashtable {
struct List *start;
};
struct Hashtable ht[26];
void init();
void insert(struct List *);
void init() {
register int j;
for (j = 0; j < 26; j++) {
ht[j].start=NULL;
}
}
int main(void) {
init();
int i = 0;
int size = 5; //size = 2 reallocation occurs
struct List *newnode = (struct List*)malloc(size * sizeof(struct List));
for (i = 0; i < 5; i++) {
if (size <= i) {
size = size * size;
struct List *temp = (struct List *)realloc(newnode, size * sizeof(*temp));
if (temp == NULL) {
printf("Realloc failed\n");
} else {
printf("realoocated\n");
newnode = temp;
}
}
scanf("%s", newnode[i].val);
insert(&newnode[i]);
}
printf("Printing\n");
for (i = 0; i < 5; i++) {
printf("%s\n", newnode[i].val);
}
free(newnode);
return 0;
}
void insert(struct List *node) {
if (ht[node->val[0] - 97].start == NULL) {
ht[node->val[0] - 97].start = node;
return;
} else {
printf("The value is %s\n", ht[node->val[0] - 97].start->val);
}
}
Output with reallocation:
struct
sample
The value is struct
realoocated
string
The value is
ascii
realoocated
alpha
The value is ascii
Printing
struct
sample
string
ascii
alpha
Output without reallocation
struct
sample
The value is struct
string
The value is struct
ascii
alpha
The value is ascii
Printing
struct
sample
string
ascii
alpha