creating Typedef pointers to Typedef structs in C

17,971

Solution 1

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;

Solution 2

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.

Solution 3

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.

Share:
17,971
newprint
Author by

newprint

Updated on June 05, 2022

Comments

  • newprint
    newprint almost 2 years

    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 !

  • Christoph
    Christoph over 13 years
    your last paragraph is wrong as you can use a forward declaration; see Jens' answer for example code ( stackoverflow.com/questions/4481603/… )