简体   繁体   中英

Pointer to own type in struct?

Is it possible?

typedef struct {
    listLink *next;
    listLink *prev;

    void *data;
} listLink;

Yes, with this syntaxis

struct list {
    int   value;
    struct list  *next;
};

or

typedef struct list
{
      int value;
      struct list *next; 
} list;

Yes, but the typedef doesn't happen until later in the statement so you need to give the struct itself a name. Eg

struct listLink {
    struct listLink *next;
    struct listLink *prev;

    void *data;
};

And you can wrap that in a typedef if you don't want to have to declare each instance as struct listLink <whatever> .

I prefer this version:

typedef struct listLink listLink ;

struct listLink{
    listLink *next;
    listLink *prev;

    void *data;
} ;

It clearly separates the struct from and members and variables.

Using the same name for both struct and typedef, struct listLink, listLink , is not an issue since they have separate namespaces.

This possible with th osgrx given syntax. Plus, this is called a linked list: http://www.ehow.com/how_2056292_create-linked-list-c.html

Choose a name, then use typedef to define it. Every linked list will need a structure, even if it only has one variable:

typedef struct product_data PRODUCT_DATA;

Define the structure. The last element should be a pointer to the type you just defined, and named "next":

struct product_data {
 int product_code;
 int product_size;
 PRODUCT_DATA *next;
};

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