一、结构体
1.概念
结构体是不同类型数据的集合,把这些数据称为结构体的成员。
结构体类型需要自己定义来说明结构体中具体由哪些类型的数据组成,所以结构体也是一种自定义类型。
2.如何定义结构体类型
语法格式:
struct<结构体标签>{
成员类型 成员名;
成员类型 成员名;
… … ;
成员类型 成员名;
};
例如:定义一个学生的类型
struct student{
int sno;
char name[20];
float score;
};
3.如何定义结构体变量
1)常规定义方式(最常用)
struct student{
int sno;
char name[20];
float score;
};
struct student st; //st为结构体变量
struct student st1,st2; //st1,st2为结构体变量
2)与类型同时定义方式
struct student{
int sno;
char name[20];
float score;
}st1,st2; //st1,st2为结构体变量
3)直接定义方式(最不常用)
struct {
int sno;
char name[20];
float score;
}st1,st2; //st1,st2为结构体变量
4.结构体变量的初始化
//与数组类似
1)完全初始化
struct student st = {1001,“Jack”,98.56};
2)部分初始化
struct student st1 = {1001,“jack”};
struct student st2 = {1001};
3)指定成员初始化
struct student st = {.name = “Jack”,98.56,sno = 1002};
5.赋值和打印
1)赋值
注意:
//与数组相似,结构体变量也不能整体赋值,例如:
struct student st ;
st = {1001,“Jack”,98.56}; //错误
//只能分别给结构体中的每一个成员赋值,例如:
st.sno = 1002 ;
strcpy(st.name,“Jack”);
st.score = 87.87;
//同类型结构体变量之间可以互相赋值,例如:
struct student st1 = {1001,“Jack”,98.56};
struct student st2;
st2 = st1; //相互赋值
2)打印
只能分别打印每一个成员,例如:
struct student st1 = {1001,“Jack”,98.56};
printf("%d %s %.2f\n",st.sno,st.name,st.score);
6.结构体数组
元素为结构体类型的数组称为结构体数组,例如:
struct student st[5] ; //st[0],st[1],st[2],st[3],st[4]都是结构体类型的变量。
例如:
#include <stdio.h>
#include <string.h>
//定义一个结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
int n,i;
printf("请输入学生人数:");
scanf("%d",&n);
struct student st[n];
for(i = 0; i < n; i++){
printf("请输入一个学生的信息:");
scanf("%d%s%f",&st[i].sno,st[i].name,&st[i].score);
}
printf("学生的信息如下:\n");
printf("-------------------------\n");
printf("sno name score\n");
printf("-------------------------\n");
for(i = 0; i < n; i++){
printf("%d %s %.2f\n",st[i].sno,st[i].name,st[i].score);
}
return 0;
}
7.结构体指针
保存结构体变脸地址的指针变量称为结构体指针变量,简称结构体指针。
例如:定义一个结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
struct student st = {1001,"Jack",98.56};
struct student * ps;
ps = &st; //结构体指针保存结构体变量的地址
printf("%d %s %.2f\n",st.sno,st.name,st.score);
printf("%d %s %.2f\n",(*ps).sno,(*ps).name,(*ps).score);
printf("%d %s %.2f\n",ps->sno,ps->name,ps->score);
return 0;
}