结构指针的兼容性

编程入门 行业动态 更新时间:2024-10-28 20:20:01
本文介绍了结构指针的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有两个结构:

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"

更多推荐

结构指针的兼容性

本文发布于:2023-11-03 09:12:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554780.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:兼容性   指针   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!