是由C标准保证本code? [英] Is this code guaranteed by the C standard?

查看:94
本文介绍了是由C标准保证本code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读,如果声明两个结构是这样的:

I have read that if you declare two structs like this:

struct Node {
   int a, b, c;
};

struct DerivedNode {
   struct Node base;
   int d, e, f;
};

然后你可以用指针来他们是这样的:

Then you can use pointers to them like this:

struct DerivedNode myDerivedNode; 
struct Node *regularNode = (struct Node *) &myDerivedNode;

regularNode->a = 3;

在换言之,地址偏移 A,B,C 是在结构节点和相同的结构DerivedNode 。这样你就可以得到一种多态性出来的吧,在那里你可以在强行(结构节点*)通过 -cast DerivedNode指针只要一个节点指针通常会采取。

In other words, the address offsets for a, b, c are the same within struct Node and struct DerivedNode. So you can get a kind of polymorphism out of it, where you can pass in a forcibly (struct Node *)-cast DerivedNode pointer wherever a Node pointer would normally be taken.

我的问题是这样的行为是否有保证。我知道有一些奇怪的内存对齐问题,编译器有时重新排序字段,以实现更好的内存包装。请问字段以往任何时候都位于任何地方,但结构DerivedNode

My question is whether this behavior is guaranteed. I know there are some weird memory alignment issues and that the compiler sometimes reorders fields to achieve better packing in memory. Will the base field ever be located anywhere but the beginning of struct DerivedNode?

推荐答案

这是保证该标准的工作。成员结构都奠定了顺序的顺序指定和第一个成员总是出现在偏移0。

This is guaranteed to work by the standard. Members in structs are layed out sequentially in the order you specify and the first member always appears at offset 0.

从ANSI C标准的相关摘录:

Relevant excerpts from the ANSI C standard:

一个结构是一类的成员组成的一个序​​列,其存储在有序序列被分配

A structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence.

这规定,成员依次布局。

This states that the members are laid out sequentially.

有可能是一个结构对象内无名填充,但不是在其开头。

There may be unnamed padding within a structure object, but not at its beginning.

这第一构件被放置在该装置偏移0

The means that the first member is placed at offset 0.

注意:从ISO / IEC第6.7.2.1采取标准摘录9899:TC3 2007年9月草案

Note: Standard excerpts taken from section 6.7.2.1 of ISO/IEC 9899:TC3 September 2007 draft.

这篇关于是由C标准保证本code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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