我想实现一个哈希表。我得到了上面的错误,但我敢说我已经正确地声明了我所有的结构体/类型。(抱歉,我还在学习C语言)错误发生在test.c的while循环中,我在这里放置了//error。怎么了?
test.c
#include "mentry.h"
#include "mlist.h"
int main() {
FILE *fPtr = fopen("S.txt", "r");
MList *ml = ml_create();
MEntry *m2;
int i = 1;
while ((m2 = me_get(fPtr)) != NULL) {
unsigned long int hash = me_hash(m2, ml->numbuckets); // ERROR HERE
i++;
}
return 0;
}
mlist.c
#include "mentry.h"
#include "mlist.h"
#define NUMBUCKETS 3
#define BUCKETSIZE 5
typedef struct bucket {
int size; // number of elements in this bucket
MEntry *entries; // array of MEntries
} Bucket;
typedef struct mlist {
int numbuckets; // number of buckets
Bucket **buckets; // an array of Bucket pointers
} MList;
/* ml_create - creates a new mailing list
- returns pointer to start of mailing list*/
MList *ml_create(void) {
MList *ml = malloc(sizeof(MList));
ml->numbuckets = NUMBUCKETS; // random initial number
// will increment once a bucket is full
// init Buckets
int b;
for (b=0; b<ml->numbuckets; b++) {
Bucket *bk = malloc(sizeof(Bucket));
bk->size = 0;
bk->entries = calloc(BUCKETSIZE, sizeof(MEntry));
ml->buckets[b] = bk;
}
return ml;
}
mlist.h
#ifndef _MLIST_H_
#define _MLIST_H_
#include "mentry.h"
typedef struct mlist MList;
/* ml_create - creates a new mailing list
- returns pointer to start of mailing list*/
MList *ml_create(void);
#endif /* _MLIST_H_ */
当您试图访问main
中的ml->numbuckets
时,它所知道的关于m1
类型的信息如下:
typedef struct mlist MList;
它知道MList
是一个结构类型,但它不知道里面有什么。
你需要把完整的定义放在mlist.h
:
#ifndef _MLIST_H_
#define _MLIST_H_
#include "mentry.h"
typedef struct mlist {
int numbuckets; // number of buckets
Bucket **buckets; // an array of Bucket pointers
} MList;
/* ml_create - creates a new mailing list
- returns pointer to start of mailing list*/
MList *ml_create(void);
#endif /* _MLIST_H_ */
怎么了?
只有当MList
的完整定义在该行可见时,才能使用ml->numbuckets
。
由于MList
的完整定义仅在mlist.c中可见,因此只能在该文件中访问struct
的成员。
unsigned long int me_hash_list(MEntry* m1, MList* m2);
并在mlist.c中定义为:
unsigned long int me_hash_list(MEntry* m1, MList* m2)
{
return me_hash(m1, m2->numbuckets);
}
,然后从main
调用me_hash_list
。
while ((m2 = me_get(fPtr)) != NULL) {
unsigned long int hash = me_hash_list(m2, ml);
i++;
}