(C) struct member reference-& gt; (arrow) and. (point), member arrow

Source: Internet
Author: User

(C) Structure member reference-> (arrow) and. (point), member arrow

The reference of struct members has the following rule:

Arrow (->): the pointer must be left;
Point (.): The object must be on the left.

So if a struct pointer references a member and the member is a struct (and an entity), what should we do if we want to reference the member?

After the experiment, we found that the above rule is still followed: the pointer must be on the left of the arrow, and the object must be referenced with a point number. For example C-> student. age

Eg.

Start with the arrow c-> s1-> age

#include "stdio.h"int main(){    struct student{        int age;        int class_;    };    struct class2{        struct student s1;    };    struct class2 *c;    struct class2 cc={    .s1={        .age=9,        .class_=2    }    };    c=&cc;    printf("%d",c->s1->age);    return 0;}

The following error occurs:

If you change the code to c-> s1.age, the Code is as follows:

#include "stdio.h"int main(){    struct student{        int age;        int class_;    };    struct class2{        struct student s1;    };    struct class2 *c;    struct class2 cc={    .s1={        .age=9,        .class_=2    }    };    c=&cc;    printf("%d",c->s1.age);    return 0;}

The compilation result is obtained:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.