【发布时间】:2012-01-31 22:17:24
【问题描述】:
假设我们有两个结构体:
typedef struct Struct1
{
short a_short;
int id;
} Struct1;
typedef struct Struct2
{
short a_short;
int id;
short another_short;
} Struct2;
从Struct2 * 转换为Struct1 * 是否安全? ANSI 规范对此有何评论?
我知道一些编译器可以选择重新排序结构字段以优化内存使用,这可能会导致两个结构不兼容。无论编译器标志如何,有什么方法可以确保此代码有效?
谢谢!
【问题讨论】:
-
重新排序标准 AFAIK 不允许成员。我相信虽然插入不同数量的填充是允许的。
-
@delnan 哦,那么 struct 'packing' 只会禁用对齐?谢谢,我不知道!