Reputation: 7136
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 !
Upvotes: 3
Views: 18548
Reputation: 61478
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;
Upvotes: 13
Reputation: 78903
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.
Upvotes: 4
Reputation: 36852
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
.
Upvotes: 2