结构体
定义:用户自定义的数据类型,在结构体中可以包含若干不同数据类型的成员变量(也可以相同),使这些数据项组合起来反映某一个信息。
格式:
struct 结构体名
{
数据类型 成员变量1;
数据类型 成员变量2;
数据类型 成员变量3;
};
结构体变量
概念:通过结构体类型定义的变量。
格式:struct 结构体名 变量名;
- 先定义结构体,再定义结构体变量
struct 结构体名
{
成员变量;
};
struct 结构体名 变量名;
- 定义结构体的同时,定义结构体变量
struct 结构体名
{
成员变量;
}变量名;
- 缺省结构体名定义结构体变量
struct
{
成员变量;
}变量名;
赋值
- 定义变量时直接用大括号赋值
struct student
{
int id;
int age;
float score;
char name[32];
};
struct student stu={1,20,76,"zhangsan"};
- 定义变量时未初始化,然后对变量单独赋值
struct student
{
int id;
int age;
float score;
};
struct student stu;
stu.id=2;
stu.age=56;
stu.score=20;
- 点等法赋值
struct student
{
int id;
int age;
float score;
};
struct student stu={
.id = 3,
.age = 30,
.score = 90
};
重定义typedef
- 定义结构体的同时重定义
typedef struct student
{
int id;
int age;
float score;
}STU;
struct student stu;// == STU stu;
- 先定义结构体,然后重定义
struct student
{
int id;
int age;
float score;
};
typedef struct student STU;
STU stu;
结构体数组
概念:结构体类型相同的变量组成的数组。
定义格式:
- 定义结构体同时定义结构体数组
struct student
{
int id;
int age;
float score;
}stu[5];
- 先定义结构体,然后定义结构体数组
struct student
{
int id;
int age;
float score;
};
struct student stu[5];
初始化
- 定义结构体同时赋值
struct student
{
int id;
int age;
float score;
}stu[5]={
{1,20,56},
{2,21,57},
{3,22,57},
{4,29,57},
{5,23,57}
};
- 先定义结构体数组,再对数组的每一个元素分别赋值
struct student
{
int id;
int age;
float score;
}stu[5];
stu[0].id=1;
stu[0].age=20;
stu[0].score=98.6
结构体数组输入输出(for循环)
struct student
{
int id;
int age;
float score;
}stu[5];
int i;
for(i=0;i<5;i++)
scanf("%d %d %f",&stu[i].id,&stu[i].age,&stu[i].score);
结构体指针
概念:指向结构体变量的指针
定义格式:struct 结构体名 *结构体指针名;
赋值:指针变量名->成员变量名 例:p->id = 1;
大小:本质是指针,4字节
结构体大小
- 字节对齐原则
用结构体里面最大的数据类型的大小和4进行比较,按照字节数小的为单位开辟空间,结构体的大小必须满足所有成员(不考虑数组和内套结构体)的整数倍.
- 节省空间原则
减少空间浪费
struct std
{
char ch;
short a;
double d;
int b;
}//大小为16
7106

被折叠的 条评论
为什么被折叠?



