Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a typedef struct containing pointers to itself?

Tags:

c

struct

typedef

I am writing a LinkedList in C, the below code represent my Node definition.

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

I understand (or think that I do) that struct Node not the same as typedef struct Node. Granted my code compiles and runs as it's supposed to, however, I get a lot of warnings when assigning next and prev (warning: assignment from incompatible pointer type). I am guessing that this has to do with how I'm defining them in the Node structure. I uploaded the full source here

So, if that is indeed the problem, how should I define next and prev inside the typedef struct Node?

I was worried this may be a repost, but couldn't quite find what I was looking for. Thanks.

like image 399
Kenny Cason Avatar asked Oct 21 '10 13:10

Kenny Cason


People also ask

Can a structure struct contain a pointer to itself?

A structure containing a pointer to itself is not a problem. A pointer has a fixed size, so it doesn't matter how big the size of the structure it points to is. On most systems you're likely to come across, a pointer will be either 4 bytes or 8 bytes in size.

Can a struct reference itself?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature.

How do you declare a variable in a typedef struct?

The purpose of typedef is to give a name to a type specification. The syntax is: typedef <specification> <name>; After you've done that, you can use <name> much like any of the built-in types of the language to declare variables.


1 Answers

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.

like image 70
unwind Avatar answered Sep 22 '22 16:09

unwind