结构体

结构体是不同类型的变量的集合, 与数组相反, 数组是相同类型变量的集合

定义

示例: 定义一个名为 house 的结构体,有三种方式:

定义结构体和定义变量分开

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
struct house {
char location[20];
int area;
int price;
};
int main() {
struct house kangqiao;
return 0;
}

定义结构体同时定义变量

1
2
3
4
5
6
7
8
9
#include <stdio.h>
struct house {
char location[20];
int area;
int price;
}kangqiao;
int main() {
return 0;
}

只为一个变量定义结构体

1
2
3
4
5
6
7
8
9
#include <stdio.h>
struct {
char location[20];
int area;
int price;
}kangqiao;
int main() {
return 0;
}

初始化和引用

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
struct house {
char location[20];
float area;
int price;
};
int main() {
struct house kangqiao = {'昌邑', 132.0, 5000}; # 位置、面积、价格
return 0;
}

结构体指针

结构体的内存对齐方式

对齐规则

  1. 第一个成员在结构体变量偏移量为 0 的地址处。
  2. 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。对齐数 = 编译器默认的一个对齐数与该成员大小中的较小值。vs 中默认值是 8 Linux 默认值为 4.
  3. 结构体总大小为最大对齐数的整数倍。(每个成员变量都有自己的对齐数)
  4. 如果嵌套结构体,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是所有最大对齐数(包含嵌套结构体的对齐数)的整数倍。