Access Item in Nested Structure in C

前端 未结 2 736
执笔经年
执笔经年 2021-01-24 01:40

I try to access \"next\" in another structure, but failed although i have tried many ways.

Here is the nested structure:

struct list_head {
    struct l         


        
相关标签:
2条回答
  • 2021-01-24 01:53

    In your definition, you are defining list to be an object as below

    typedef struct {
        char *key;
        char *value;
        struct list_head list; // This is an object
    }dict_entry;
    

    Hence, you will de-reference next through the . operator as d->list.next. The first level of de-referencing i.e. d->list requires -> operator as d is defined to be a pointer. For next, since list is an object and not a pointer, you would have to use . operator.

    0 讨论(0)
  • 2021-01-24 02:18

    list is not declared as a pointer, so you don't use the -> operator to get its members, you use the . operator:

    while (d->list.next != NULL) {
    }
    

    A different fix:

    typedef struct {
      char *key;
      char *value;
      struct list_head *list;
    }dict_entry;
    

    This way, your original code attempting to refer to next would compile.

    0 讨论(0)
提交回复
热议问题