假设我们有两个结构:
typedef struct Struct1 { short a_short; int id; } Struct1; typedef struct Struct2 { short a_short; int id; short another_short; } Struct2;它是安全的从 Struct2 * 转换为 Struct1 * ?什么是ANSI规范说这件事?我知道,一些编译器可以重新排列结构领域优化内存使用,这可能使两个结构不兼容的选项。有没有什么办法,以确保这个code将是有效的,无论编译器标志呢?
Is it safe to cast from Struct2 * to Struct1 * ? What does the ANSI spec says about this? I know that some compilers have the option to reorder structs fields to optimize memory usage, which might render the two structs incompatible. Is there any way to be sure this code will be valid, regardless of the compiler flag?
感谢您!
推荐答案结构类型的指针总是在C进行同样的重新presentation。
struct pointers types always have the same representation in C.
(C99,6.2.5p27)所有的指针结构类型应具有相同的 再presentation和对齐要求对方。
(C99, 6.2.5p27) "All pointers to structure types shall have the same representation and alignment requirements as each other."
和结构类型的成员总是为了用C
And members in structure types are always in order in C.
(C99,6.7.2.1p5)的结构是由一个序列的类型 成员,其存储在一个有序的序列分配
(C99, 6.7.2.1p5) "a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence"
更多推荐
结构指针的兼容性
发布评论