简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM