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);
}