我正在创建以下结构指针类型:
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"我假设这是因为我定义的struct将其自身包含为一个字段。我怎样才能避免这种情况?有没有办法前向声明structs?
谢谢!
发布于 2013-11-29 14:12:28
当编译器涉及到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;发布于 2013-11-29 14:11:50
你不能这样做...你可以的
// 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!!!https://stackoverflow.com/questions/20279437
复制相似问题