Under these declarations, what types are the follo

2019-03-07 03:24发布

问题:

struct place 

{

    char name[80+1];
    double latitude;
    double longitude;
};

struct node

{

    struct place city;
    struct node *next;

};

struct node *head;


head
head -> city
head -> next
head -> city -> name
head -> next ->city.name

These kinds of tasks always make me lose points on exams, anyone kind enough to explain? It's asking about what types the variables mentioned are, and I guess stuff like head are simply a pointer towards the value of entire structure node?

回答1:

In the later snippet at the later part,

head -> city -> name

is wrong, because, city is not a pointer type. You need to use the dot operator (.) to access a member of a non-pointer structure variable. Just the way you've used it in

head -> next ->city.name

Other than that, syntactically, the snippets appear fine.

Just to add, as a basic sanity, you should be checking for non-NULL-ity of a pointer before de-referencing to avoid invoking undefined behavior.