1.结构体类型的声明
//声明一个结构体 关键字—struct
//例 声明一个学生类型,通过学生类型来创建学生对象
struct Stu {
char name[20];
char tele[12];
char sex[10];
int age;
};
int main() {
struct Stu s1;
struct Stu s2;
return 0;
}
2.结构体变量的定义和初始化
struct S {
char ch;
double num;
char arr[15];
};
int main() {
//结构体的初始化
struct S s = { 'a',3.14,"hello world!" };
printf("%c %lf %s\n", s.ch, s.num, s.arr);
}
3.结构体内存对齐
struct S1 {
char ch;
int a;
char ch1;
};
struct S2 {
char ch;
char ch1;
int a;
};
struct S3 {
char ch;
char ch1;
char ch3;
};
int main() {
struct S1 s1 = { 0 };
printf(“%d\n”, sizeof(s1));
struct S2 s2 = { 0 };
printf(“%d\n”, sizeof(s2));
struct S3 s3 = { 0 };
printf(“%d\n”, sizeof(s3));
}
大小分别是12,8,3
对齐规则
1.第一个成员在与结构体变量偏移量为0的地址处。
2.其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。对齐数=编译器默认的一个对齐数与该成员大小的较小值。vs中默认的为8.
3.结构体总大小为最大对齐数的整数倍
4.如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是所有最大对齐数的整数倍。
具体讲解https://www.bilibili.com/video/BV1q54y1q79w
4.结构体传参
struct S{
char ch;
double num;
int a;
};
void Init(struct S temp) {
temp.ch = 'm';
temp.num = 3.14;
temp.a = 12;
}
void Init1(struct S* p) {
p->ch='m';
p->num=3.14;
p->a=12;
}
void Print(struct S temp) {
printf("%c %lf %d\n", temp.ch, temp.num, temp.a);
}
void Print1(struct S* p) {
printf("%c %lf %d\n", p->ch, p->num, p->a);
}
int main() {
struct S s = { 0 };
Init(s);
Init1(&s);
Print(s);
Print1(&s);
}