递归Struct Typedef

时间:2013-11-29 06:08:51

标签: c struct

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

typedef struct hashmap_item {
    hashmap_item_t prev;
    hashmap_item_t next;
    char* key;
    void* value;
    int time_added;
} *hashmap_item_t;

但是我收到以下错误:

hashmap.h:5: error: expected specifier-qualifier-list before "hashmap_item_t"

我假设这是因为我定义的结构包含自己作为一个字段。我怎么能避免这个?有没有办法转发结构?

谢谢!

2 个答案:

答案 0 :(得分:5)

当编译器出现prevnext成员的声明时,它会尝试查找标识符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;

答案 1 :(得分:4)

你不能这样做......你可以

// C,C++ allows pointers to incomplete types.
typedef struct hashmap_item *hashmap_item_t;

struct hashmap_item {
    hashmap_item_t prev;
    hashmap_item_t next;
    char* key;
    void* value;
    int time_added;
};  // Till this point the structure is incomplete. 

当编译器开始解析你的代码时,它会发现hashmap_item_t以前没有在任何地方声明过。因此,它会抛出错误信息。

typedef struct hashmap_item {
    hashmap_item_t prev; // Compiler was unable to find 'hashmap_item_t'
    hashmap_item_t next; // Compiler was unable to find 'hashmap_item_t'
    char* key;
    void* value;
    int time_added;
} *hashmap_item_t;// But 'hashmap_item_t' identifier appears here!!!