這是我在某個論壇上看到的一個採訪問題。我一直在試圖弄清楚它是如何工作的,但我不太明白。有人可以解釋它是如何工作的嗎?問:給定一個指向結構內成員a的指針,寫一個返回結構指針的例程。給定一個指向結構內成員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);
}
什麼**你問**嗎? – 2010-06-20 02:28:32
對不起,我在標題中有問題,但不是帖子本身。現在已經修復了。 – Steve 2010-06-20 02:31:24