访问另一个struct中的struct字段

时间:2014-05-17 22:06:08

标签: c generics hash struct linked-list

所以我的数据结构应该是一个哈希表,一个链表列表。每个链表中都有一个链表。在这些链表中是一本书。书籍包含书名,以及包含该书的图书馆ID的链接列表。

我在链接列表中搜索是否已经存在book->名称。 我知道如何通过以下方式访问所谓的“架子”:

int index = hashFunction(char* nameOfBook) % this->size;

然后在哈希数组中搜索以找到它:

this->chain[index]

但是当我进入链表时,如何访问Book结构?

在list.h中

typedef struct NodeStruct {
    void *data;
    struct NodeStruct* next;
    struct NodeStruct* prev;
} NodeStruct;

typedef struct ListStruct {
    NodeStruct* first;
    NodeStruct* last;
    int elementType;
} ListStruct;

在hash.c中:

typedef struct Book {
    ListStruct* libID; // Each book has its own list of library IDs
    char* name; // Each book has a name.
} Book;

// A hashset contains a linked list of books.
typedef struct HashStruct {
    int size;
    int load;
    ListStruct **chain; //An array of Linked Lists.
} HashStruct;

以下是构造函数:

// Constructor for a 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 a linked list.
    for (int i = 0; i < size; ++i) {
        tempHash->chain[i] = newList(sizeof(Book));
    }
    return tempHash;
}

编辑:我我得到了它的工作。尚未测试。

bool has_hashset (HashHandle this, char *item) { 
    //Finds the index to look 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;
}

很抱歉,如果这非常令人困惑。顺便说一句,链表的“数据”是通用的。 谢谢!

1 个答案:

答案 0 :(得分:1)

因为cur->data是指向void的指针,所以需要将其指定为Book类型的指针(或将其转换为该类型)。否则,您将无法使用->来获取成员,因为void不是结构。

您在编辑中修复的内容应该可以正常使用。