如何以一种可移植的方式从指向该结构的成员的指针中计算出指向该结构的开头的指针? [英] How can one calculate a pointer to the beginning of a struct from a pointer pointing at a member of the struct in a portable way?

查看:59
本文介绍了如何以一种可移植的方式从指向该结构的成员的指针中计算出指向该结构的开头的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 T1 T2 是两种类型,并给出以下结构:

Assume T1 and T2 are two types and the following struct is given:

struct s
{
  T1 x;
  T2 y;
}

进一步,假设我们有一个 struct s 类型的对象:

Further, assume that we have an object of type struct s:

struct s a;

由此,我们可以计算出指向对象第二个struct成员的指针:

From this, we can calculate a pointer to the second struct member of the object:

T2 *q = &s.y;

我正在寻找的是一种从 q 计算类型为 struct s * 的指针 p 的可移植方式,使得p 指向对象 a .

What I am looking for is a portable way to calculate from q a pointer p of type struct s * such that p points at the object a.

推荐答案

给出 T2 * q =& sy; ,然后 char * x =(char *)q-offsetof(struct s,y); 定义一个指向 s 的第一个字节的 x . offsetof 宏在< stddef.h> 中定义.

Given T2 *q = &s.y;, then char *x = (char *) q - offsetof(struct s, y); defines an x that points to the first byte of s. The offsetof macro is defined in <stddef.h>.

然后可能会期望 struct s * p =(struct s *)x; 定义一个指向 s p ,具体取决于人们希望如何解释C标准.(标准没有明确定义将指向 char 的指针转换为指向它的第一个字节的结构的指针.我们可以采用标准的规范,将指针转换回",在C 2018 6.3.2.3 7,以涵盖这种情况的原始类型.)我希望它可以在所有常规C实现中使用.

One might then expect struct s *p = (struct s *) x; define a p that points to s, depending on how pedantically one wishes to interpret the C standard. (The conversion of a pointer to char to a pointer to the structure it is the first byte of is not explicitly defined by the standard. We can take the standard’s specification that a pointer "converted back," in C 2018 6.3.2.3 7, to its original type to cover this case.) I expect it to work in all normal C implementations.

这篇关于如何以一种可移植的方式从指向该结构的成员的指针中计算出指向该结构的开头的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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