簡體   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