一.引言
之前我们接触过 int ,flaot ,double ,char 类型的数据,而今天我们将接触结构体类型的数据。
结构体其实是一个具有相同或者不同类型元素集合。
二.组成
法.一:
首先,声明一个结构体。
struct student{
int t; //元素
double a; //元素
char ar[13];
//根据需求定义所需要的类型。
};
定义一个结构体:
struct student stu1;(定义一个struct student 类型的元素)
struct student stu2[10]; (定义含有10个struct student 类型结构体的数组)
法.二:
struct student{
int t; //元素
double a; //元素
char ar[13];
}stu1,stu2[10];
在声明结构体时,定义变量元素。
法.三:
使用typedef (作用起别名)
typedef struct student{
int a;
char b;
};
student stu;(定义一个struct student类型的结构体变量stu)等价于struct student stu;
三.初始化
struct student {
int a ;
char ar[15];
};
struct student s1={12,"asdas"}; (只能整体初始化)。
s2=s1;(类型一样,直接赋值)
——————————————————
四.结构体元素访问
通过变量的地址访问结构体中的元素。
scanf("%d%s",&s1.a,s1.ar);
printf("%d",s2.a);
struct student *p=&s1;
printf("%d %s",p->a,p->ar);
五.结构体数据储存原理
对齐系数:现主流CPU为64为,取8字节比较高效,因此默认字节数为8,结构体成员首地址为8的倍数(并非所有编译器都有默认对齐系数)若无,则变量的大小为该元素对齐系数。
如下:
struct stu{ 自身大小 默认对齐系数 实际对齐系数
char a ; 1 8 1
int b; 4 8 4
char c; 1 8 1
};
1000 | |
1001 | |
1002 | |
1003 | |
1004 | (对齐到4的倍数) |
1005 | |
1006 | |
1007 | (到这结束,占4位) |
1008 | |
结尾为最大实际对齐系数倍数,(1008)为(4)的倍数。
不是整倍数,补。如(1009)补到(1012),即(1012)为4的倍数。
目录
对齐系数:现主流CPU为64为,取8字节比较高效,因此默认字节数为8,结构体成员首地址为8的倍数(并非所有编译器都有默认对齐系数)若无,则变量的大小为该元素对齐系数。