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 !

newprint
  • 6,936
  • 13
  • 67
  • 109
  • Possible duplicate of [C typedef of pointer to structure](https://stackoverflow.com/questions/1543713/c-typedef-of-pointer-to-structure) – Evan Carroll Jan 28 '19 at 21:22

3 Answers3

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;
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
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.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
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.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111