2014-05-17 6 views
0

내 데이터 구조는 연결된 목록의 배열 인 해시 테이블로 간주됩니다. 각 연결된 목록에는 연결된 목록이 있습니다. 그리고 그 연결된 목록 안에는 책이 있습니다. 책은 책 이름과 그 책을 보유하는 라이브러리 ID의 링크 된 목록을 포함합니다.다른 구조체 내에서 구조체 필드에 액세스

링크 된 목록에서 책> 이름이 이미 있는지 검색하는 데 문제가 있습니다. 다음과 같이 그것을 찾기 위해 해시 배열 내에서 검색 후

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

과 : 나는 그것이 의해 있다는 소위 "선반"에 접근하는 방법을 알고

this->chain[index] 

을하지만 방법에 액세스 할 수 있습니다 일단 내가 연결된 목록 안에 있다면 Book 구조체? 되는 hash.c에서 list.h

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

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

에서

:

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

편집 : 나는 그것을 가지고 생각 다음

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; 

는 생성자이다 작업. 아직 테스트하지 않았습니다.

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

매우 혼란스러운 경우 죄송합니다. 그런데 연결된 목록의 '데이터'는 일반적인 것입니다. 감사합니다.

+0

for (int i = 0; i chain [i] = newList (sizeof (Book *));}'의미가 없습니다. 아마도 : for (int i = 0; i chain [i] = NULL;}'? – wildplasser

+0

안녕하세요, 왜 모든 연결된 목록을 초기화하는 것이 좋지 않습니까? 각각을 별도로 초기화하는 것이 더 좋습니까? – Mickey

답변

1

cur->datavoid에 대한 포인터이므로 Book 유형의 포인터에 할당해야합니다 (또는 해당 유형으로 캐스팅해야 함). 그렇지 않으면 void이 (가) 구조체가 아니기 때문에 ->을 사용하여 멤버를 얻을 수 없습니다.

수정 사항을 수정하면 올바르게 작동합니다.

+0

편집 해 주셔서 감사합니다. 교정하지 않았습니다. – McLovin

+0

그것은 나에게 segfault 오류를주는거야 : ( – Mickey

관련 문제