Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 265
Reuben Crimp Avatar asked Oct 14 '25 09:10

Reuben Crimp


1 Answers

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;
like image 173
Casper Beyer Avatar answered Oct 17 '25 01:10

Casper Beyer