c - Accessing struct field within another struct -
so data structure supposed hash table, array of linked list. inside each of linked list holds linked list. , inside linked list book. book contains book name, , linked list of library ids hold book.
i'm having trouble searching within linked list see if book->name exists. know how access called "shelf" it's on by:
int index = hashfunction(char* nameofbook) % this->size;
and searching within hash array find this:
this->chain[index]
but how can access book struct once i'm inside linked list?
in list.h
typedef struct nodestruct { void *data; struct nodestruct* next; struct nodestruct* prev; } nodestruct; typedef struct liststruct { nodestruct* first; nodestruct* last; int elementtype; } liststruct;
in hash.c:
typedef struct book { liststruct* libid; // each book has own list of library ids char* name; // each book has name. } book; // hashset contains linked list of books. typedef struct hashstruct { int size; int load; liststruct **chain; //an array of linked lists. } hashstruct;
here constructors:
// constructor new book. book *newbook(char* name) { book *this = malloc (sizeof (book)); assert(this != null); this->name = name; this->libid = malloc(sizeof (liststruct*)); this->libid = newlist(sizeof(int)); return this; } hashhandle new_hashset(int size) { hashhandle temphash = malloc (sizeof (hashstruct)); assert (temphash != null); temphash->size = size; temphash->load = 0; temphash->chain = malloc (sizeof (liststruct)); assert(temphash->chain != null); // each linked list holds linked list. (int = 0; < size; ++i) { temphash->chain[i] = newlist(sizeof(book)); } return temphash; }
edit: think got work. haven't tested yet.
bool has_hashset (hashhandle this, char *item) { //finds index at. int index = strhash(item) % this->size; nodestruct *cur = this->chain[index]->first; while (cur != null) { book *tmp = cur->data; if (strcmp(tmp->name, item) == 0) return true; cur = cur->next; } return false; }
sorry if confusing. way, 'data' of linked list generic. thank you!
because cur->data
pointer void
, need assign pointer of type book
(or cast type). otherwise, not able use ->
member because void
not struct.
what fixed in edit should work fine.
Comments
Post a Comment