newprint
newprint

Reputation: 7136

creating Typedef pointers to Typedef structs in C

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

Answers (3)

Karl Knechtel
Karl Knechtel

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

Jens Gustedt
Jens Gustedt

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

Etienne de Martel
Etienne de Martel

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

Related Questions