1

I want to avoid having to write struct before every time I create a new struct variable, so I'm typedefing it.

The following doesn't work:

typedef struct {
    int data;
    Node *next;
} Node;

This does though:

struct Node {  
  int date; 
  struct Node *next;  
};

How do I use a typedef struct in C? I keep getting this error with the above one:

error: unknown type name 'Node'
            Node *next;
user212541
  • 1,878
  • 1
  • 21
  • 30
  • 2
    possible duplicate of [self referential struct definition?](http://stackoverflow.com/questions/588623/self-referential-struct-definition) – nwellnhof Feb 27 '14 at 23:19
  • Actually a duplicate of [Declaration rule in struct typedef](http://stackoverflow.com/questions/13303168/declaration-rule-in-struct-typedef). – nwellnhof Feb 27 '14 at 23:22

2 Answers2

2

The typedef doesn't take effect until the whole typedef statement has ended.

I haven't tried it, but you might be able to typedef against a forward reference:

typedef struct Node_struct Node;
struct Node_struct {  
  int date; 
  Node *next;  
};

You can certainly do it the other way around

struct Node_struct {  
  int date; 
  struct Node_struct *next;  
};
typedef struct Node_struct Node;
keshlam
  • 7,931
  • 2
  • 19
  • 33
1

You can typedef struct Node to Node, but the typedef isn't completed when you reference Node. Therefore you must type struct Node. My previous edit was incorrect because the struct didn't have a name, which will cause problems with pointers.

typedef struct Node {
    int data;
    struct Node *next;
} Node;