gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:33:26 25 4
gpt4 key购买 nike

所以我的数据结构应该是一个哈希表,一个链表数组。每个链表内部都有一个链表。在这些链接列表中是一本书。一本书包含书名以及保存该书的图书馆 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;
}

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

最佳答案

因为cur->data是一个指向void的指针,所以需要将它赋给Book类型的指针(或者将其强制转换为Book)到那种类型)。否则,您将无法使用 -> 来获取成员,因为 void 不是结构。

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

关于c - 访问另一个结构中的结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com