简体   繁体   English

使用指针访问struct内部的struct

[英]Access struct inside struct with pointers

I have 2 structs interlinked. 我有2个结构相互关联。 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. 我正在构建一个查找函数来比较Item结构。

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 ? 更具体地说,我可以在if语句上执行list-> item-> text ,还是必须执行(* 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 . 你有什么, (*list).(*item).text ,会导致语法错误,因为你必须有一个结构成员. operator. 运营商。

Can I do list->item->text on the if statement? 我可以在if语句中执行list->item->text吗?

Yes, since both are pointers. 是的,因为两者都是指针。


Recall that a->b is the same as (*a).b . 回想一下a->b(*a).b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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