gpt4 book ai didi

c - 给定一个指向结构中成员 a 的指针,编写一个返回指向该结构的指针的例程

转载 作者:太空狗 更新时间:2023-10-29 16:51:31 25 4
gpt4 key购买 nike

这是我在某个论坛上看到的一道面试题。我一直在试图弄清楚它是如何工作的,但我不太明白。有人可以解释一下它是如何工作的吗?

问题:给定一个指向结构中成员 a 的指针,编写一个返回指向该结构的指针的例程。

struct s 
{
...
int a;

};

struct s *get_s_ptr(int *a_ptr)
{
// implement this.
}

答案是:

struct s* get_s_ptr(int *a_ptr)
{
return (struct s*)((char*)a_ptr - (int)&((struct s*)0)->a);
}

最佳答案

How does it work?

这里的基本等式(所有算术以字节为单位)是

address of struct member s->a == s + byte offset of a

给定 s 的类型、单个编译器和单个目标机器,他们确定了 a 的字节偏移量——它对于类型 s 的每个结构都是相同的.

你得到了左侧,你的面试官要求你恢复s。你可以通过得到一个新的等式来做到这一点;两边减去字节偏移量:

address of struct member s->a - byte offset of a == s

在这个问题中,给定 s->a 的地址,但您必须计算出字节偏移量。为此,您再次使用原始方程并将s设置为零:

address of struct member s->a where s is zero == zero + byte offset of a 
== byte offset of a

C 中的左侧构建如下

struct pointer s where s is zero                            (struct s *)0
struct member s->a where s is zero ((struct s*)0)->a
address of s->a where s is zero &((struct s*)0)->a

最后的步骤:

  1. 为了使算术在 C 中合法,这个字节偏移被强制转换为一个整数。
  2. 为了确保减法是以字节为单位完成的,a_ptr 被强制转换为 char *
  3. 为了给结果正确的类型,将差异转换为 struct s *

附录:正如 Eli Bendersky 指出的那样,您应该尽量避免需要此代码的情况。几乎总有更好的方法。

关于c - 给定一个指向结构中成员 a 的指针,编写一个返回指向该结构的指针的例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3078002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com