![c7e1b92d281f36105b7d944a80292f75.png](https://i-blog.csdnimg.cn/blog_migrate/cb8591ed7efcd98789f64fa3906b9335.jpeg)
声明及使用
#include int main(){ struct Stu{ int age; // 4个字节 char projects[3]; // 3个字节 int score; // 4个字节 }; struct User{ char gender; // 1 short age; // 2 int number; // 4 }; printf("User size is %lu ", sizeof(struct User)); // User size is 8 struct Stu jack; printf("jack size is %lu ", sizeof(jack)); // jack size is 12 return 0;}
结构体可以存放多种类型的不同数据,提供一种灵活的方式
内存对齐的问题
可以看到User的内存大小为8字节,而不是1+2+4= 7, 由于内存对齐的问题,这里以4个字节对齐
![fc5f0bb0abde7cc3d2bac06f2924d338.png](https://i-blog.csdnimg.cn/blog_migrate/da967ffb3699a1099e7b7f2e041bca31.jpeg)
内存对齐
我们看到Stu的总大小为12个字节,而不是4+3+4字节,这里跟上面的对齐原理是一致的
赋值取值
#include int main(){ struct Stu{ int age; // 4个字节 char projects[3]; // 3个字节 int score; // 4个字节 }; struct User{ char gender; // 1 short age; // 2 int number; // 4 }; printf("User size is %lu ", sizeof(struct User)); // User size is 8 struct Stu jack; printf("jack size is %lu ", sizeof(jack)); // jack size is 12 jack.age = 1; printf("jack age is %d ", jack.age); // jack age is 1 return 0;}
成员的更新、获取都通过 . 操作进行
结构体的指针
#include int main(){ struct Stu{ int age; // 4个字节 char projects[3]; // 3个字节 int score; // 4个字节 }; struct User{ char gender; // 1 short age; // 2 int number; // 4 }; printf("User size is %lu ", sizeof(struct User)); // User size is 8 struct Stu jack; printf("jack size is %lu ", sizeof(jack)); // jack size is 12 jack.age = 1; printf("jack age is %d ", jack.age); // jack age is 1 struct User user; user.age = 1; // 结构体的指针 struct User *user_pointer; user_pointer = &user; printf("userpointer is %p ", user_pointer); printf("user age is %d ", user_pointer->age); return 0;}
当我们改变struct的成员顺序发现一个有趣的现象
struct User占用内存变为了12字节,之前是8字节,这是由于成员顺序变更导致内存对齐时的大小发生变化,char gender要对齐四个字节,short age 也要对齐四个字节,由于中间隔着int number 导致无法紧凑存放,因此总内存占用变为 4*3 = 12
#include int main(){ struct Stu{ int age; // 4个字节 char projects[3]; // 3个字节 int score; // 4个字节 }; struct User{ char gender; // 1 int number; // 4 short age; // 2 }; printf("User size is %lu ", sizeof(struct User)); // User size is 12 struct Stu jack; printf("jack size is %lu ", sizeof(jack)); // jack size is 12 jack.age = 1; printf("jack age is %d ", jack.age); // jack age is 1 struct User user; user.gender = 's'; user.age = 1; user.number = 22; // 结构体的指针 struct User *user_pointer; user_pointer = &user; printf("userpointer is %p ", user_pointer); printf("user age is %d ", user_pointer->age); return 0;}
![49f96edc8c93c1447f38e44a4780cc16.png](https://i-blog.csdnimg.cn/blog_migrate/f49f68391f643f07485d9c0942fa0ebf.jpeg)
成员顺序影响结构体大小