kkontagion kkontagion - 1 month ago 21
C Question

"Dereferencing pointer to incomplete type", typedefs are ok

I'm trying to implement a hash table. I get the above error but AFAIK I've properly declared all my structs/typedefs. (I'm still learning C, sorry)
The error occurs in test.c in my while loop, where I've put //ERROR. What's wrong?

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_ */

Answer

At the time you attempt to access ml->numbuckets in main, all it knows about the type of m1 is this:

typedef struct mlist MList;

It knows that MList is a structure type, but it knows nothing about what's in it.

You need to put the full definition in 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_ */
Comments