Search code examples
cpointersstructqualifiers

Can a struct have a member which is a pointer to a struct of the same type?


Sounds super convoluted, but it's a simple concept. Say you have some struct "foo" one if it's members is a pointer to another foo struct (like a linked list)

Which seems to work.

struct foo {
   struct foo* ptr;
};

But what if I wanted foo to be a type?

Like how would I do the following?

typedef struct foo {
   foo* ptr;
} foo;

The declaration of ptr fails since foo is not a qualifier yet.


Solution

  • Forward declare the definition.

    typedef struct foo {
        struct foo* ptr
    } foo;
    

    Or you could forward declare the type declaration.

    typedef struct node_t node_t;
    
    typedef struct node_t {
       node_t *next;
    } node_t;