1

I'm creating the following struct pointer type:

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

But I get the following error:

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

I'm assuming this is because the struct I'm defining contains itself as a field. How can I avoid this? Is there a way to forward-declare structs?

Thanks!

1
  • I would like the struct to contain hashmap_item_t's, which are pointers to hashmaps... is the only way to get it to work to do hashmap_item* as the field?
    – Paul B
    Commented Nov 29, 2013 at 6:12

2 Answers 2

6

When the compiler comes to the declaration of the prev and next members, it tries to find the identifier hashmap_item_t, but it hasn't been declared yet. In C all identifiers must be declared before they can be used.

You have two choices: Either declare the typedef before the structure (yes it's legal); Or use a structure declaration such as:

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

you can't do like that... you can

// 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. 

When the compiler starts parsing your code, It will find hashmap_item_t has not been declare anywhere previously. So, it will throw a error message.

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!!!
1
  • Or else use the structure declaration as suggested by @Joachim Pileborg
    – user1814023
    Commented Nov 29, 2013 at 6:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.