c - C程序中的struct和union如何分配内存?
问题描述
在结构中,将为结构内的所有成员创建内存空间。在联合中,只会为需要最大内存空间的成员创建内存空间。考虑以下代码:
struct s_tag
{
int a;
long int b;
} x;
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
union u_tag
{
int a;
long int b;
} y;
这里 struct 和 union 内部有两个成员:int 和 long int。int 的内存空间为:4 字节,long int 的内存空间为:8
因此,对于 struct 4+8=12 个字节将被创建,而 8 个字节将被创建用于联合。我运行以下代码来查看证明:C
#include<stdio.h>
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
int main()
{
printf("Memory allocation for structure = %d", sizeof(x));
printf("\nMemory allocation for union = %d", sizeof(y));
return 0;
}
但我可以看到以下输出:
Memory allocation for structure = 16
Memory allocation for union = 8
为什么 struct 的内存分配是 16 而不是 12?我的理解有什么错误吗?
解决方案
很可能需要在 X 字节边界上对齐内存访问。此外,这取决于编译器——它可以做自己喜欢的事情。
推荐阅读
- javascript - SlateJS + 还原
- jquery - Free-jqgrid 工具栏搜索和标题分组
- php - 通过 PHP 将表单详细信息提交到 JSON 并发送到服务器
- python - 日志轮换监督日明智
- python - “django.db.utils.IntegrityError:” NOT NULL 约束失败:adopts_pet.submission_data
- javascript - Java math.random 不会在函数内随机化?
- python - 如何从数据库中读取数据并将其显示在 PyQt 表中
- python - PyOrient SQL 查询内存错误
- angular - 为所有可观察对象上的所有订阅编写中间件
- html - H1 额外的填充没有被移除