为什么iOS中的结构对齐方式不同

Why struct alignment different in iOS

本文关键字:对齐 方式不 结构 iOS 为什么      更新时间:2023-10-16

我已经将Xcode中的结构对齐设置为8字节打包。例如:

struct Info
{
    unsigned short  kindID;
    char            kindName[32];
    int64_t         gameMonery;
}__attribute__ ((aligned(8)));

此结构体大小为48字节,在iPhone5和iPhone 5S中,kindName地址偏移量为2字节,但在iPhone 5中,gameMoney偏移量为36字节,在iPhone 5S中gameMoney偏移量为40字节。

为什么会有这种不同?

在32位平台上,64位类型(int64_t)的对齐为4,在64位平台上为8。

通过在声明中添加__attribute__((packed)),可以使编译器抑制各个元素的对齐。未对齐成员的访问速度稍慢。

结构的大小在两个平台上没有差异的原因是大小取决于结构的对齐(指定为8):

示例:

struct { char i; } __attribute__((aligned(8))) foo;
sizeof(foo) == 8;