我在这里看到很多关于解除对不完整类型的指针的问题,但是它们中的每一个都与不使用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));
答案 0 :(得分:1)
此代码
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;
答案 1 :(得分:0)
正如Andrew指出的那样,声明“struct stable_s {...}”会使事情编译。
但是,你没有说这是一个课堂作业还是现实世界。如果是现实世界,那么自己声明结构可能是一个非常糟糕的主意。您将获得一个用于引用库的opaque类型;你不应该知道或访问里面的东西。该库依赖于您可能会陷入困境的各种语义,随着软件版本的变化,结构的内容可能(并且几乎肯定会)发生变化,因此您的代码将来会中断。