C - compiler error: dereferencing pointer to incomplete type

C - compiler error: dereferencing pointer to incomplete type

我在这里看到很多关于取消引用指向不完整类型的指针的问题,但每一个问题都与不使用 typedef 或在 .c 中而不是在头文件中声明结构有关。我已经尝试解决这个问题好几个小时了,但似乎找不到办法。

stable.h(不可更改):

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

编译器错误(使用标志 -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));

这段代码

 typedef struct stable_s *SymbolTable;

将类型 SymbolTable 定义为指向 struct stable_s 的指针。

这段代码

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

定义类型 stable_s 的结构。请注意 stable_s 不是 struct stable_s.

简单

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

没有 typedef 将解决您的问题。

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

正如安德鲁指出的那样,声明一个 "struct stable_s { ... }" 将使事情编译。

但是,您没有说明这是 class 作业还是现实世界。如果在现实世界中,自己声明结构可能是一个非常糟糕的主意。你被赋予了一个不透明的类型来引用一个库;你不应该知道或访问里面的东西。该库依赖于您可能会搞砸的各种语义,并且随着软件版本的变化,结构的内容可能(并且几乎肯定会)发生变化,因此您的代码将来会中断。