首页 > 解决方案 > 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?我的理解有什么错误吗?

标签: c

解决方案


很可能需要在 X 字节边界上对齐内存访问。此外,这取决于编译器——它可以做自己喜欢的事情。


推荐阅读