【问题标题】:Accessing struct field within another struct访问另一个结构中的结构字段
【发布时间】:2014-07-06 03:52:21
【问题描述】:

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

我在链接列表中搜索以查看书名是否已存在时遇到问题。 我知道如何访问它所在的所谓“架子”:

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

对不起,如果这很混乱。顺便说一句,链表的“数据”是通用的。 谢谢!

【问题讨论】:

  • for (int i = 0; i &lt; size; ++i) {tempHash-&gt;chain[i] = newList(sizeof(Book*));} 毫无意义。也许:for (int i = 0; i &lt; size; ++i) {tempHash-&gt;chain[i] = NULL;} ?
  • 您好,为什么不能初始化所有的链表呢?分别初始化每个更好吗?

标签: c generics hash struct linked-list


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多