结构指针的兼容性 [英] Struct pointer compatibility

查看:145
本文介绍了结构指针的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个结构:

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"

这篇关于结构指针的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆