1. 匿名结构体
可以在定义结构体的同时使用它,不需要先声明一个类型名。
typedef struct {
int data[MaxSize]; // 最多存储多少元素
int length; // 当前长度
} Sqlist;
// 使用
Sqlist L;
2. 前向声明
在你需要先引用结构体但在当前作用域中尚未定义该结构体时,可以使用前向声明。
typedef struct Sqlist Sqlist;
struct Sqlist {
int data[MaxSize]; // 最多存储多少元素
int length; // 当前长度
};
// 使用
Sqlist L;
3. 嵌套结构体
你可以在一个结构体内部定义另一个结构体。
typedef struct Sqlist {
int data[MaxSize]; // 最多存储多少元素
int length; // 当前长度
} Sqlist;
typedef struct {
Sqlist list; // 嵌套使用
int other_data;
} AnotherStruct;
// 使用
AnotherStruct AS;
4. 灵活的数组成员
在C99和后续版本中,你可以在结构体中定义具有未知大小的数组。
typedef struct {
int data[]; // 灵活的数组大小
int length;
} Sqlist;
// 使用
Sqlist L;
int n = 10;
L.data = malloc(n * sizeof(int));
L.length = n;
5. 动态大小的数组
使用动态内存分配来处理不确定大小的数据。
typedef struct {
int *data; // 指向动态分配的数组
int length;
} Sqlist;
// 使用
Sqlist L;
L.length = 10;
L.data = malloc(L.length * sizeof(int));
6. 指针代替数组
有时,使用指针来代替数组可以提供更多的灵活性。
typedef struct {
int *data; // 指向动态分配的数组
int length;
} Sqlist;
// 使用
Sqlist L;
L.length = 10;
L.data = malloc(L.length * sizeof(int));