Node
的结构,其第一个成员是 Node* p_next
p_head
&p_head
类型的 Node**
转换为 Node*
,并将其存储在 p_node_before_head
中。这样我就可以将 *p_node_before_head
视为一个节点,其中 p_node_before_head->p_next
的值就是 p_head
#include <iostream>
struct Node{
Node* p_next;
int item;
};
int main(){
Node head = {nullptr, 5};
Node* p_head = &head;
//By pretending that "p_head" is a node whose first element is a pointer to the head,
//we create a new pointer that points to this "node before the head"
Node* p_node_before_head = reinterpret_cast<Node*>(&p_head);
Node* p_head2 = p_node_before_head->p_next;
std::cout << p_head2->item << std::endl;
}
这是重新解释强制转换未定义的行为吗? 我对如何确定是否将一种类型的指针强制转换为另一种类型的指针感到有点困惑
pointer-interconvertibility
。
不,这是未定义的行为。您永远不能假装某种类型的对象存在于您从未显式(或隐式)创建此类类型的对象的某个内存位置。
在地址
&p_head
处有一个Node*
对象,但没有Node
对象。因此 reinterpret_cast
的结果不能指向任何 Node
对象,因此成员访问 p_node_before_head->p_next
具有未定义的行为。
指针可互换性甚至不重要,因为首先在相关地址处没有相关的
Node
对象。所以肯定不存在任何可以与 Node*
对象进行指针互换的对象。