3

Have a question about typedef in C.

I have defined struct:

typedef struct Node { int data; struct Node *nextptr; } nodes; 

How would I create typedef pointers to struct Node ??

Thanks !

1

3 Answers 3

13

You can typedef them at the same time:

typedef struct Node { int data; struct Node *nextptr; } node, *node_ptr; 

This is arguably hard to understand, but it has a lot to do with why C's declaration syntax works the way it does (i.e. why int* foo, bar; declares bar to be an int rather than an int*

Or you can build on your existing typedef:

typedef struct Node { int data; struct Node *nextptr; } node; typedef node* node_ptr; 

Or you can do it from scratch, the same way that you'd typedef anything else:

typedef struct Node* node_ptr; 
Sign up to request clarification or add additional context in comments.

Comments

4

To my taste, the easiest and clearest way is to do forward declarations of the struct and typedef to the struct and the pointer:

typedef struct node node; typedef node * node_ptr; struct node { int data; node_ptr nextptr; }; 

Though I'd say that I don't like pointer typedef too much.

Using the same name as typedef and struct tag in the forward declaration make things clearer and eases the API compability with C++.

Also you should be clearer with the names of your types, of whether or not they represent one node or a set of nodes.

Comments

2

Like so:

typedef nodes * your_type; 

Or:

typedef struct Node * your_type; 

But I would prefer the first since you already defined a type for struct Node.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.