递归Struct Typedef

Pau*_*l B 1 c struct

我正在创建以下结构指针类型:

typedef struct hashmap_item {
    hashmap_item_t prev;
    hashmap_item_t next;
    char* key;
    void* value;
    int time_added;
} *hashmap_item_t;
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

hashmap.h:5: error: expected specifier-qualifier-list before "hashmap_item_t"
Run Code Online (Sandbox Code Playgroud)

我假设这是因为我定义的结构包含自己作为一个字段.我怎么能避免这个?有没有办法向前声明结构?

谢谢!

Som*_*ude 5

当编译器来到prev 和next成员的声明时,它会尝试查找标识符hashmap_item_t,但尚未声明它.在C中,必须先声明所有标识符,然后才能使用它们.

你有两个选择:要么在结构typedef 之前声明(是的,它是合法的); 或者使用结构声明,例如:

typedef struct hashmap_item {
    struct hashmap_item *prev;
    struct hashmap_item *next;
    char* key;
    void* value;
    int time_added;
} *hashmap_item_t;
Run Code Online (Sandbox Code Playgroud)