简体   繁体   中英

C - compiler error: dereferencing pointer to incomplete type

I've seen many questions here about dereferencing pointers to incomplete types but every single one of them is related to not using typedef or to having the structs declared in the .c, not in the header file. I've been trying to fix this for many hours and can't seem to find a way.

stable.h (cannot be changed):

typedef struct stable_s *SymbolTable;

typedef union {
    int i;
    char *str;
    void *p;
} EntryData;

SymbolTable stable_create();

stable.c:

SymbolTable stable_create() {
    SymbolTable ht = malloc(sizeof (SymbolTable));
    ht->data = malloc(primes[0] * sizeof(Node));
    for (int h = 0; h < primes[0]; h++) ht->data[h] = NULL;
    ht->n = 0;
    ht->prIndex = 0;
    return ht;
}

aux.h:

#include "stable.h"

typedef struct {
    EntryData *data;
    char *str;
    void *nxt;
} Node;


typedef struct {
    Node **data;
    int n;
    int prIndex;
} stable_s;

typedef struct {
    char **str;
    int *val;
    int index;
    int maxLen;
} answer;

freq.c:

answer *final;
static void init(SymbolTable table){
    final = malloc(sizeof(answer));
    final->val = malloc(table->n * sizeof(int));
}

int main(int argc, char *argv[]) {
    SymbolTable st = stable_create();
    init(st);
}

compiler error (using flags -Wall -std=c99 -pedantic -O2 -Wextra):

freq.c:13:30: error: dereferencing pointer to incomplete type ‘struct stable_s’
 final->val = malloc(table->n * sizeof(int));

This code

 typedef struct stable_s *SymbolTable;

defines the type SymbolTable as a pointer to struct stable_s .

This code

typedef struct {
    Node **data;
    int n;
    int prIndex;
} stable_s;

defines a structure of type stable_s . Note that stable_s is not struct stable_s .

A simple

struct stable_s {
    Node **data;
    int n;
    int prIndex;
};

without the typedef will solve your problem.

See C : typedef struct name {...}; VS typedef struct{...} name;

As Andrew points out, declaring a "struct stable_s { ... }" will make things compile.

However, you don't say whether this is a class assignment or real-world. If real-world, it's probably an extremely bad idea to declare the struct yourself. You are being given an opaque type to use to reference a library; you are not supposed to know or access the stuff inside. The library is relying on various semantics that you might mess up, and as software versions change, the contents of the struct can (and almost certainly will) change, so your code will break in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM