Mr.Y
Mr.Y

Reputation: 875

Reference to pointer vs Pass by reference?

What is the difference between CodeA and CodeB below?: They are both syntactically correct and it seems both code will be able to modify the original pointer "head".

Please correct me if I'm wrong

Code A: (Pass by reference)

NodeType *head = new NodeType();
insertNode(*head, val);
void insertNode(NodeType &head, int val) {}

Code B: (Reference to Pointer)

NodeType *head = new NodeType();
insertNode(head, val);
void insertNode(NodeType *&head, int val) {}

EDIT Would like to add what situation Code A is preferable and vice versa?

Upvotes: 1

Views: 66

Answers (1)

flogram_dev
flogram_dev

Reputation: 42888

it seems both code will be able to modify the original pointer "head"

Wrong. Only code B will be able to modify the head pointer. Code A receives the NodeType object pointed to by head, not the pointer.

what situation Code A is preferable and vice versa?

Code A is preferable when the function only needs a NodeType object.

Code B is preferable when the function needs to modify the pointer value, e.g. changing it to point to another NodeType object.

Upvotes: 4

Related Questions