数据结构对齐, #pragma pack 和 __attribute__((packed))

本文介绍了GCC中两种调整数据结构对齐方式的方法:#pragma pack和__attribute__((packed))。通过示例展示了它们如何影响结构体的大小和成员偏移,包括无对齐优化的情况以及使用指定对齐值的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gcc中定义了两个修改数据结构对齐方式的语句

1. #pragma pack()

2. __attribute__((packed))

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// calculate the offset of t in S
#define offsetof(S,t)     (size_t)&(((S *)0)->t)   

typedef struct _S1{
    char a;
    char b;
    double c;
}S1;

//__attribute__((packed)) means no alignment optimization
typedef struct _S2{
    char a;
    char b;
    double c;
}__attribute__((packed)) S2;   

typedef struct _Y
{
    int a;
    int b;
    char c;
    char content[0];
} Y;

#pragma pack(push, 4)
struct a_4
{
    short v1;
    int v2;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct a_1
{
    short v1;
    int v2;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值