"取消引用指向不完整类型"的指针,typedef就可以了

时间:2016-10-16 03:31:12

标签: c struct types dereference

我试图实现哈希表。我得到了上面的错误,但是AFAIK我已经正确地声明了我的所有结构/ typedef。 (我还在学习C,对不起) 在我的while循环中test.c中发生错误,我在其中放置了// 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_ */

2 个答案:

答案 0 :(得分:1)

  

出了什么问题?

只有在该行显示ml->numbuckets的完整定义时,才能使用MList

由于MList的完整定义仅在mlist.c中可见,因此您只能在该文件中访问struct的成员。

执行此操作的一种方法是在mlist.h中声明一个函数:

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

然后从me_hash_list致电main

while ((m2 = me_get(fPtr)) != NULL) {
  unsigned long int hash = me_hash_list(m2, ml);
  i++;
}

答案 1 :(得分:1)

当您尝试访问ml->numbuckets中的main时,所有人都知道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_ */