一、建立结构体类型
struct Data
{
int month;
int day;
int year;
} ;
struct Student
{
int num;
char name[20];
char sex;'
int age;
struct Data birthday;
char addr[30];
};
1struct 是声明结构体类型时所用的关键字,不能省略;
2花括号最后的分号不能省略;
3成员可以属于另一个结构体;
二、定义结构体变量
在声明的时候同时定义变量;自我感觉这个是常用的,个人比较中意这个;但是也要根据具体的使用来选择。
struct student
{
…
}student1,studnet2;//定义变量
同时也可以不指定类型名而直接定义结构体类型变量。
struct
{
…
}student1,studnet2;//定义变量
这种方法就不能再以结构体类型取定义其他的变量,没啥用。
三、结构体变量的初始化和引用
对成员赋值:
student1.num = 100;
“.” 是成员运算符,在所有运算符中的优先级最高,把Student1.num看作为一个整体来看待,相当于一个变量。
Warning:不能企图输出结构体变量名来达到输出结构体变量所有成员的值。
Printf(“%s\n”,student1);//不正确
四、一个结构体数组的例子
#include<stdio.h>
struct Student
{
int num;
char name[20];
float score;
};
int main()
{
struct Student stu[5] = {
{10101,"zhang",78},{10103,"wang",98.5},{10106,"li",86},
{10108,"ling",73.5},{10110,"sun",100}
};
struct Student temp;
const int n = 5;
int i,j,k;
printf("The,order is:\n");
for(i = 0;i<n-1;i++)//选择排序
{
k = i;
for(j = i+1;j<n;j++)
if(stu[j].score>stu[k].score)
k = j;
temp = stu[k];stu[k] = stu[i];stu[i] = temp;
}
for(i = 0;i<n;i++)
printf("%6d %8s %6.2f\n",stu[i].num,stu[i].name,stu[i].score);
printf("\n");
return 0;
}
运行结果:
五、结构体变量和结构体变量的指针做函数参数
#include<stdio.h>
#define N 3
struct Student
{
int num;
char name[20];
float score[3];
float aver;
} ;
int main()
{
void input(struct Student stu[]);//函数声明
struct Student max(struct Student stu[]);//函数声明
void print(struct Student stu);//函数声明
struct Student stu[N],*p = stu; //定义结构体数组和指针
input(p);
print(max(p));
return 0;
}
void input(struct Student stu[])
{
int i;
printf("please input the students' message:\n");
for(i = 0;i<N;i++)
{
scanf("%d %s %f %f %f",&stu[i].num,&stu[i].name,
&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]);
stu[i].aver = (stu[i].score[0] + stu[i].score[1] + stu[i].score[2]) / 3.0;
}
}
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("\n成绩最高为:\n");
printf("学号:%d\n 姓名:%s\n 三门课成绩:%5.1f,%5.1f,%5.1f\n 平均成绩:%6.2f\n",
stud.num,stud.name,stud.score[0],stud.score[1],stud.score[2],stud.aver);
}