- I have a struct called
Nodewhose first member isNode* p_next - I have a pointer to the first node called
p_head - I want to cast
&p_headwhich is of typeNode**to aNode*, and store it inp_node_before_head. This is so I can treat*p_node_before_headas if it were a node where the value ofp_node_before_head->p_nextis the value ofp_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;
}
Is this reinterpret cast undefined behaviour?
I am bit confused on how to determine whether casting a pointer of one type to a pointer of another type follows pointer-interconvertibility.
&p_headaNode**the same type asNode*? No it's not so dereferencingp_node_before_headis UB and breaks strict-aliasing rules. See Type aliasing for more details.reinterpret_cast(or C-style casts) you should take that as an indication that you are probably doing something wrong. In most cases, allreinterpret_castallows you to do is later cast back to the original type and then use that.