Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c - How to define a typedef struct containing pointers to itself?

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.

question from:https://stackoverflow.com/questions/3988041/how-to-define-a-typedef-struct-containing-pointers-to-itself

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...