结构体指针怎么用

来源:互联网 发布:卡乐比麦片辐射 知乎 编辑:程序博客网 时间:2024/06/11 03:42

目的:

利用结构体指针输出同一个学生的学号

#include <iostream>#include <string>using namespace std;struct student{int ID;string name;};int main(){student stu;student *p = &stu;//定义结构体指针,并初始化。这步一定要有,有指针就要有对应的对象。不能光定义指针。stu.ID = 1001;stu.name = "Julia"; //建立结构体具体对象并赋值cout << stu.ID << endl; cout << (*p).ID << endl;cout << p->ID << endl; //这3行说明 stu.ID和(*p).ID和p->ID是同一回事system("pause");return EXIT_SUCCESS;}

编程收获:

1. 如果使用结构体指针,就要定义结构体对象,并且让两者对应

2. 结构体指针和结构体对象都可以调用结构体的内容。有三种办法,见程序倒数第5行-倒数第三行

运行结果如下:


0 0
原创粉丝点击