结构体的字节对齐

  1. 结构体的字节对齐:
在C语言里,结构体所占的内存是连续的,但是各个成员之间的地址不一定是连续的。所以就出现了"字节对齐".
 
结构体变量的大小,一定是其最大的数据类型的大小的整数倍,如果某个数据类型大小不够,就填充字节。
结构体变量的地址,一定和其第一个成员的地址是相同的。
 
1) 结构体字节对齐 
#include <stdio.h>
#include <string.h>
 
struct Box
{
// 首先检查结构体成员里最大的数据类型是 double, 占8个字节,则
int height;   // 系统判断 int 可以和相邻的 char name[10] 共同填充字节
char name[10]; // char name[10] 需要填充 到double 的倍数,但是可以和相邻的 int 一起累加,再填充4个字节,对齐 double 的2倍
double width;   // double 是所有成员里最大数据类型,满足double 的1倍
char type;   // char 会填充7个字节,对齐double 的1倍
};
 
int main(void)
{
struct Box box;
box.height = 4; // 高度
strcpy(box.name, "Dropbox");   // 名称
box.width = 5.5;   // 宽度
box.type = 'C';   // 类型
 
printf("box = %p\n", &box);
printf("box.height = %p\n", &box.height);
printf("box.name = %p\n", box.name);
printf("box.width = %p\n", &box.width);
printf("box.type = %p\n", &box.type);
 
printf("box = %d\n", sizeof(box));   // 16 + 8 + 8 = 24
return 0;
}
 
 
 
2) 初识链表
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
struct Student
{
char *name;   // 姓名
int age;   // 年龄
struct Student *next;
// next 是结构体成员,但是类型是 struct Student * 类型,用来指向某个 struct Student 的结构体变量的。
// 结构体可以看做是一个自定义的数据类型,而且结构体可以嵌套,但是嵌套有条件:
// 结构体只可以嵌套自身类型的结构体指针,但是绝对不能嵌套自身类型的结构体变量
// 比如,不能嵌套 struct Student next; 这种
};
 
int main(void)
{
struct Student stu, *stup;   // 定义了一个结构体变量 stu 和 一个结构体指针变量 stup
 
stu.name = (char *)malloc(10 * sizeof(char));   // 给姓名申请了一个10个字节的堆空间
strcpy(stu.name, "damao");   // 拷贝字符串 "damao" 给 stu.name (注意,不能直接赋值,要用拷贝)
stu.age = 18;   // 今年 18岁了
 
 
stup = (struct Student *)malloc(1 * sizeof(struct Student));   // 给 stup 申请一个堆空间,用来保存两个指针(name,next)和一个int
stup->name = (char *)malloc(10 * sizeof(char));   // 给 stup->name 申请一个堆空间,保存字符串
strcpy(stup->name, "ermao");   // 拷贝字符串
stup->age = 16;   // 今年 16岁了
 
stu.next = stup;   // stu的成员next 指向了 结构体变量 stup 的首地址,链表诞生
stup->next = NULL;   // stup的成员 next 指向 NULL, 保证安全。
 
free(stup->name);   // 最后申请的堆 最先释放
free(stup);   // 继续释放
free(stu.name);   // 最先申请的堆 最后释放
 
return 0;   // 程序正常结束
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值