詳細闡述StenSoft評論,如果您只知道data
成員的值,您將無法獲取包含它的結構。
但如果你知道它的地址,說T** member_addr
你可以找到node
:
void * ma = static_cast<void *>(member_addr); // convert pointer to void * : legal
intptr_t ima = static_cast<intptr_t>(ma); // convert void * to intptr_t : legal
intptr_t ina = ima - offsetof(struct node, data); // legal by definition of offestof
void * na = static_cast<void *>(ina); // convert intptr_t to void * : legal
struct node *pn = static_cast<node *>(na); // convert void * to pointer : legal provided the initial void * pointer points to a correct object
當然,所有這只是合法的C++ 11或以上。
你不能移植它。您可能會發現一種攻擊'offsetof'宏和reinterpret_cast <>''char *'和'node *'之間的所有東西的方法,但這在技術上是未定義的行爲。如果您需要表達雙向關係,則使用從每個子節點到其父節點的指針。 – 2015-02-08 12:54:15
你在問如何找到列表的頭部? 'T *數據;'看起來很奇怪BTW。 – 2015-02-08 12:55:30
你真的有指向成員('pointer ==&node.data')的指針,還是你有指針存儲在該成員中('pointer == node.data')?如果是後者,你找不到它。 – StenSoft 2015-02-08 13:06:02