简体   繁体   中英

Access struct inside struct with pointers

I have 2 structs interlinked. These forming a linked list.

typedef struct  {
    char *text;
    int count;
} *Item;

typedef struct node {
    Item item;
    struct node *next;
} *link;

I am building a lookup function to compare the Item structs.

link lookup(link head, Item item){
    link list;
    for(list = head; list != NULL; list = list->next)
        if(strcmp(list->item->text, item->text) == 0)
            return list;
    return NULL;
}

More specifically, can I do list->item->text on the if statement or do I have to do (*list).(*item).text ? Or is this not possible at all?

You can do what you want, except you used the wrong syntax for the second form. The following are equivalent:

list->item->text

and:

(*(*list).item).text

What you had, (*list).(*item).text , will cause a syntax error, since you must have a structure member after the . operator.

Can I do list->item->text on the if statement?

Yes, since both are pointers.


Recall that a->b is the same as (*a).b .

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