1.结构体类型的声明
struct tag {
成员列表;
}变量列表;
// struct 结构体关键字
// tag 结构体标签
// struct tag 结构体类
eg:
struct Student {
char name[50];// "张三"
char birthday[50]; // "1996-09-19"
int gender; // 1
char id[100]; // "20200102"
};
2.结构体变量及初始化
#include <stdio.h>
#include <string.h>
struct Student {
char name[100];
int age;
float score;
};
int main(){
//声明结构体变量
struct Student stu;
strcpy(stu.name,"MS");
stu.age = 30;
stu.score = 8;
printf("name=%s,age=%d,score=%.2f\n",stu.name,stu.age,stu.score);
return 0;
}
结构体的不完全声明:
省略名字,直接在最后面进行命名
// 匿名结构体类型
struct {
char name[10];
char alias[10];
}type1;
// 结构体变量 type1
struct {
char name[10];
char alias[10];
}* p_type;
// 结构体指针变量 p_type
在进行命名时易出现结构体类型书写不便时使用typedef关键字给结构体类型起别名,也可对int等类型名进行重命名方便后续的修改
//typedef struct Student
{typedef struct {
char name[50];// "张三"
char birthday[50]; // "1996-09-19"
int gender; // 1
char id[100]; // "20200102"
}Stu;// 可以使用别名定义变量并初始化
Stu student = {"张三","1996-09-19",1,"20200102"}
3.结构体的自引用
自引用方式:
struct Node {
int ele;
struct Node* next; // 存放结构体指针类型的变量
//类似于链表的一个节点
};
4.结构体成员访问
#include <stdio.h>// 结构体类型
struct Student {
char name[50];// "zhangsanfeng"
char birthday[50]; // "1996-09-19"
int gender; // 1
char id[100]; // "20200102"
};
int main(){ // 使用结构体类型,创建一个该类型对应的结构体变量
struct Student stu = {"zhangsanfen","1996-09-19",1,"20200102"};
//打印学生的学号和姓名,使用.操作符(结构成员访问操作符)
printf("%s\n",stu.id);
printf("%s\n",stu.name);
// 保存stu变量的地址(保存了stu的地址后才能进行如下操作)
struct Student* p_stu = &stu;
// 利用*[解引用操作符]打印学号和姓名
printf("%s\n", (*p_stu).id);
printf("%s\n", (*p_stu).name);
//解引用后还是对应&stu
printf("%s\n",(&stu)->id);
printf("%s\n", (&stu)->name);
//通过箭头就可以直接拿到对应的值
printf("%s\n",p_stu->id);
printf("%s\n", p_stu->name);
return 0;
}
- 改变结构体变量的属性:
- 使用strcpy进行修改
- eg:strcpy(stu.name,"李四")
5.计算结构体大小
Ubuntu(gcc编译器) | char | short | int | float | double | * | |
32 | 分配空间的大 小 | 1 | 2 | 4 | 4 | 8 | 4 |
64 | 分配空间的大 小 | 1 | 2 | 4 | 4 | 8 | 8 |
32 | 位置偏移大小 | 1 | 2 | 4 | 4 | 4 | 4 |
64 | 位置偏移大小 | 1 | 2 | 4 | 4 | 8 | 8 |
#include <stdio.h>
struct MyStruct{
char c;//1字节 偏移量从0开始
int i;//4字节 偏移量从4开始(前一个的字节数加填充量得等于下一个的字节数)
double d;//8字节 (总共所占空间大小为最大字节数的整数倍)
};
int main(){
printf("Size of MyStruct: %zu\n", sizeof(struct MyStruct));
return 0;
}
为什么存在内存对齐?
- 平台的原因所谓平台原因就是与硬件有关,硬件不能访问内存中的每一个空间,换句话说,就是按一定的规律进行访问,这样内存对齐就起到了很好的作用
- 性能的原因数据结构(尤其是栈),应该尽可能的在自然边界上对齐
- 因为我们的CPU访问空间,就是一次性按四个字节的空间来访问,内存对齐在一定的时候避免了访问一次的空间进行了二次访问
- 因此我们在写结构体时应该把占字节个数小的放在一起(这样我们的内存就能节省一定的空间)
6.typedef:
功能: 给一个已经存在的类型取别名,可以通过别名来定义变量。
- 按照定义变量的方法定义一个变量
- 在定义变量该行的最前面,加上typedef 关键字,那么对应的变量名,就是类型的别名。
- 若是自定义数据类型名称较长,可以利用typedef简化类型名称
使用typedef有利于类型名的修改便于代码的修改