Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a struct referencing itself in C using custom type

I would like to create a struct with pointer to the property of the same type.

Ideally I would like to go for something like this, but this causes compilation error:

typedef struct {

  int data;
  Node *next;

} Node;

Solution I’m going for in this scenerio is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

typedef struct Node_s {

  int data;
  struct Node_s *next;

} Node_t;

Is it a valid approach or could it cause any obvious issues?

>Solution :

It is a valid and idiomatic method of declaring self-referencing structures in C.

You don’t have to introduce different names for the tag and the typedef name, the following is just as good:

typedef struct Node {
  int data;
  struct Node *next;
} Node;

There is no name clash because these names live in different namespaces.

Another valid method is like this:

typedef struct Node Node;
struct Node {
    int data;
    Node *next;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading