Here is an interview question that I saw on some forum. I’ve been trying to figure out how it works but I don’t quite get it. Could somebody explain how it works?
Q: Given a pointer to member a within a struct, write a routine that returns a pointer to the struct.
struct s
{
...
int a;
…
};
struct s *get_s_ptr(int *a_ptr)
{
// implement this.
}
The answer is:
struct s* get_s_ptr(int *a_ptr)
{
return (struct s*)((char*)a_ptr - (int)&((struct s*)0)->a);
}
The fundamental equation here (all arithmetic in bytes) is
Given the type of
s, a single compiler, and a single target machine, they determined the byte offset ofa—it’s the same for every struct of type s.You’re given the left-hand side and your interviewer asked you to recover
s. You can do this by getting a new equation; subtract the byte offset from both sides:In the problem, you’re given the address of
s->a, but you have to figure out the byte offset. To do this you use the original equation again withsset to zero:The left-hand side in C is built as follows
Final steps:
a_ptris cast tochar *.struct s *.Addendum: As Eli Bendersky points out, you should try to avoid situations where this code would be necessary. There is almost always a better way.