How to define a typedef struct containing pointers to itself?

You need to do it in this order:

typedef struct Node Node;

struct Node
{
  int value;
  Node *next;
  Node *prev;
};

That doesn’t do exactly what you asked, but it solves the problem and is how this generally is done. I don’t think there’s a better way.

This kind of forward declaration has a second usage, in data hiding. If the list was implemented in a library, you could have just the typedef in the public header, along with functions like:

Node * list_new(void);
Node * list_append(Node *head, Node *new_tail);
size_t list_length(const Node *head);

This way, users of the library don’t have easy access to the internals of your library, i.e. the fields of the Node structure.

Leave a Comment