3

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.

Reuben Crimp
  • 311
  • 4
  • 12

2 Answers2

5

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;
Casper Beyer
  • 2,203
  • 2
  • 22
  • 35
1

To go further in implementing Casper Von B's answer:

If you have a few variable types like int and maybe a char array in the struct, you will need to use malloc:

node_t *ptr = malloc(sizeof(node_t));

You can use the -> operator and . operator to choose the variable:

ptr -> x = 12;

Then, when finished use free() for garbage collection:

free(ptr);

My final note is you can continue to link structs together with pointers and then traverse through them.

fingaz
  • 241
  • 1
  • 6