1.结构体数组
如果有10个学生的基本信息需要参加运算,应该用结构体数组。它跟我们之前遇到的数值型数组不同之处:每个数组元素都是一个结构体类型的数据,分别包括若干个成员项。
struct Person
{char name[20];
int count;
};
int main()
{Person leader[3]={"Li",0,"Zhang",0"Xu",0};
//定义Person类型的数组,有3个元素,成员内容为姓名和得票数
2.指向结构体变量的指针
概念:该变量内存的起始地址
3.可以通过指针引用结构体变量中的成员,以下三种形式等价:
struct Student;
{ };
Student stu1;
Student*p=&stu1; //p指向结构体变量stu1,注意格式
1)结构体变量名.成员名 stu1.num
2)(*p).成员名 (*p).num
3)p->成员名 p->num
4.用结构体变量和指向结构体变量的指针构成链表
链表是一种数据结构,链表中有一个头指针(head),它存放一个地址,指向第一个元素。
链表中的元素称为结点,每个结点包括:
1.用户需要的实际数据
2.下一个结点的地址(最后一个元素的地址放NULL,链表结束)
struct Student
{int num;
float score;
Student *next; //next指向Student结构体变量
};
用这种方式就可以建立链表
实例(静态链表):
struct Student
{
int num;
float score;
Student *next;
};
int main()
{
student a,b,*head,*p;
a.num=1001,a.score=91;
b.num=1002,a.score=92;
head=&a;
a.next=&b;
b.next=NULL;
}
3.结构体类型数据作函数参数
1)结构体变量名作实参 较少使用,原因是形参值不能返回
2)用指向结构体变量的指针作函数实参
3)用结构体变量的引用作函数形参,它就成为实参(结构体变量)的别名(推荐:直观易懂,效率高)
第3)点举例
struct Student
{int num;
string name;
float score[3];
}stu={1001,"Nike",91,92,93};
int main()
{void print(Student&);
print(stu);
return 0;
}
void print(Student &stud)
{cout<<stud.num}