nulltorpedo
nulltorpedo

Reputation: 1205

Typedef struct definition with pointers to the said struct as its elements

so usually this typedef makes code cleaner:

typedef struct {
    int x;
} X;

What if I want to have a list that needs pointers in the struct how do I reference them?

struct X{
   int x;
   struct X * next;
}

This works, but now I don't have a typedef for this?

Upvotes: 1

Views: 164

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

You can do the typedef just like for any other structure:

typedef struct X {
    int x;
    struct X * next;
} X;

Or you can do the typedef before the structure:

typedef struct X X;
struct X {
    int x;
    X * next;
};

In the first case above, we have to reference the struct inside itself, since the typedef haven't been defined yet. In the second case we explicitly define the typedef before the struct, and can therefore use it inside.

Please note that using the same name for both the structure and the typedef can be somewhat confusing at times, but there is nothing wrong with it.

Upvotes: 3

LisztLi
LisztLi

Reputation: 242

typedef struct Y{
    int x;
    struct Y *next;
} X;

Upvotes: 0

Related Questions