繁体   English   中英

访问另一个结构中的结构字段

[英]Accessing struct field within another struct

因此,我的数据结构应该是哈希表,即链表的数组。 在每个链表中都包含一个链表。 在这些链接列表中是一本书。 一本书包含一本书的名称,以及保存该书的图书馆ID的链接列表。

我在链接列表中进行搜索时遇到麻烦,以查看是否存在book-> name。 我知道如何通过以下方式访问所谓的“架子”:

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;
}

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

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

您在编辑中修复的问题应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM