结构体基础知识点(三)--结构体指针
前期回顾
结构体指针
1. 指向结构体变量的指针
指向结构体对象的指针变量既可以指向结构体变量,也可以指向结构体数组中的元素。指针变量的基类型必须与结构体变量的类型相同。例如:
struct Student *pt // pt 可以指向 struct Student 类型的变量或数组元素
栗子1:
通过指向结构体变量的指针变量输出结构体变量中成员的信息
#include<stdio.h>
#include<string.h>
int main()
{
struct Student
{
long int num;
char name[20];
char sex[10];
float score;
};
struct Student stu_1;//定义struct Student类型的变量stu_1
struct Student *p;
p = &stu_1;
stu_1.num = 1010;
strcpy(stu_1.name, "Li Lin");//用字符串复制给stu_1.name赋值
strcpy(stu_1.sex, "Man");
stu_1.score = 89.5;
printf("num:%ld
name:%s
sex:%s
score:%5.1f
", stu_1.num, stu_1.name, stu_1.sex, stu_1.score);
printf("
num:%ld
name:%s
sex:%s
score:%5.1f
", (*p).num, (*p).name, (*p).sex, (*p).score);
return 0;
}
说明 为了事业方便直观,C语言允许把(*p).num 用 p–>num 来代替,"–>“代表一个箭头,p–>num 表示 p 所指的结构体变量中的num 成员。同样,(*p).name 等价于 p–>name。”–>"称为指向运算符。
如果p 指向一个结构体变量 stu,以下3种用法等价:
- stu.成员名(如 stu.num);
- (*p).成员名(如 (*p).num);
- p–>成员名(如 p–>num);
2. 指向结构体数组的指针
栗子2:
有3个学生的信息,放在结构体数组中,要求输出全部学生的信息
#include<stdio.h>
struct Student
{
int num;
char name[20];
char sex;
int age;
};
struct Student stu[3] = {
{
10101,"Li Lin",M,18},{
10102,"Zhang Fang",M,19},{
10104,"Wang Min",F,20} };
int main()
{
struct Student *p;
printf(" No. Name sex age
");
for (p = stu; p < stu + 3; p++)
printf("%5d %-20s %2c %4d
", p->num, p->name, p->sex, p->age);
return 0;
}
3. 用结构体变量和结构体变量的指针作函数参数
栗子3:
有n个结构体变量,内含学生学号,姓名和3门课程的成绩。要求输出平均成绩最高的学生信息(包括学号、姓名、3门课程成绩和平均成绩)
#include <stdio.h>
#define N 3
struct Student
{
int num;
char name[20];
float socre[3];
float aver;
};
void input(struct Student stu[])
{
int i;
printf("输入各学生的信息:姓名、学号、三门课成绩:
");
for(i=0;i<N;i++)
{
scanf("%d %s %f %f %f",&stu[i].num,stu[i].name,
&stu[i].socre[0],&stu[i].socre[1],&stu[i].socre[2]);
stu[i].aver=(stu[i].socre[0]+stu[i].socre[1]+stu[i].socre[2])/3;
}
}
struct Student max(struct Student stu[])
{
int i,m=0;
for(i=0;i<N;i++)
if(stu[i].aver>stu[m].aver)
m=i;
return stu[m];
}
void print(struct Student stud)
{
printf("
成绩最高的学生是:
");
printf("学号:%d
姓名:%s
三门课成绩:%5.1f,%5.1f,%5.1f
平均成绩:%6.2f
",stud.num,stud.name,stud.socre[0],stud.socre[1],stud.socre[2],stud.aver);
}
int main()
{
struct Student stu[N],*p=stu;
input(p);
print(max(p));
return 0;
}
