结构体指针(3)

作用:通过指针访问结构体中的成员。

利用操作符->可以通过结构体指针访问结构体属性。

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //1.定义结构体
 6 struct Student
 7 {
 8     string name;
 9     int age;
10     int score;
11 };
12 
13 int main(void)
14 {
15     //2.创建学生结构体变量
16     struct Student s = {"张三",18,100};
17 
18     //3.通过指针指向结构体变量
19     struct Student *p = &s;
20 
21     //4.通过指针访问结构体变量中的数据
22     cout << "姓名:" << p->name << " 年龄:" << p->age << " 成绩:" << p->score << endl;        //(1)结构体变名也可以直接访问
23                                                                                             //s.age
24                                                                                             //s.name
25                                                                                             //s.score
26     system("pause");
27     return 0;
28 }

 

posted @ 2020-04-13 11:32  坦率  阅读(156)  评论(0)    收藏  举报