内存如何在C程序中分配给结构和联合?

时间:2018-07-07 07:18:04

标签: c

在结构中,将为结构中的所有成员创建内存空间。 在联合存储空间中,将仅为需要最大存储空间的成员创建空间。 考虑以下代码:

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

因此对于结构体,将创建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?我的理解有什么错误吗?

2 个答案:

答案 0 :(得分:1)

最有可能需要在X字节边界上对齐内存访问。另外,由编译器决定-它可以执行自己喜欢的操作。

答案 1 :(得分:0)

编译器在两个struct成员之间添加不可见的填充字节,以确保long成员的地址是sizeof(long)的倍数,以便变量在内存中正确对齐。根据CPU的体系结构,如果变量未正确对齐,对它的访问可能会使程序崩溃,导致值错误,缓慢或无法按预期工作。