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

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

问题描述

假设我们有两个结构体:

Suppose we have two structs:

typedef struct Struct1
{
    short a_short;
    int id;
} Struct1;

typedef struct Struct2
{
    short a_short;
    int id;
    short another_short;
} Struct2;

Struct2 * 转换为 Struct1 * 是否安全?ANSI 规范对此有何规定?我知道一些编译器可以选择重新排序结构字段以优化内存使用,这可能会使两个结构不兼容.无论编译器标志如何,有没有办法确保此代码有效?

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?

谢谢!

推荐答案

struct 指针类型在 C 中始终具有相同的表示形式.

struct pointers types always have the same representation in C.

(C99, 6.2.5p27) "所有指向结构类型的指针应具有相同的表示和对齐要求相互一致."

(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天全站免登陆