Reputation: 1614
The following is my current code. My professor told us to use a double pointer to create an array of pointers
struct dict {
struct word **tbl;
int (*hash_fcn)(struct word*);
void (*add_fcn)(struct word*);
void (*remove_fcn)(struct word*);
void (*toString_fcn)(struct word*);
};
struct word {
char *s;
struct word *next;
};
struct dict *hashtbl;
Part of the main function
hashtbl=malloc(sizeof(struct dict));
hashtbl->tbl=malloc(sizeof(struct word)*256);
int i;
for(i=0;i<256;i++)
{
hashtbl->tbl[i]=NULL;
}
is this the correct way to implement this sort of double pointer array?
and is using
hashtbl->tbl[i] = .....
the right way of accessing that space?
Upvotes: 0
Views: 803
Reputation: 21019
To initialize struct word **tbl
:
hashtbl->tbl = malloc(sizeof(struct word *)*256);
if (hashtbl->tbl == NULL) {
printf("Error malloc");
exit(1);
}
for (int i = 0; i < 256; i++) {
hashtbl->tbl[i] = malloc(sizeof(struct word));
if (hashtbl->tbl[i] == NULL) {
printf("Error malloc");
exit(1);
}
To deallocate:
for (int i = 0; i < 256; i++) {
free(hashtbl->tbl[i]);
}
free(hashtbl->tbl);
hashtbl->tbl = NULL;
Upvotes: 0
Reputation: 894
hashtbl->tbl=malloc(sizeof(struct word)*256);
should actually be
hashtbl->tbl=malloc(sizeof(struct word *)*256);
since hashtbl->tbl
is an array of struct word *
Upvotes: 3