Home  >  Article  >  Backend Development  >  Pitfalls of calling method by pointer?

Pitfalls of calling method by pointer?

WBOY
WBOYforward
2024-02-09 18:06:08537browse

Pitfalls of calling method by pointer?

In PHP programming, pointers are a powerful tool that can be used to reference the memory address of a variable and then modify the value of the variable. However, there may be some pitfalls and problems when calling methods with pointers, which need to be handled with caution. In this article, PHP editor Banana will introduce in detail the pitfalls of pointer calling methods to help developers avoid common mistakes and unnecessary troubles. Whether you are a beginner or an experienced developer, this article will provide you with practical guidance and advice. Let's explore the pitfalls of pointer calling methods and improve our programming skills!

Question content

I am writing an implementation of 2-3-4 trees. The node structure is as follows

type Node struct {
    items  []int
    childs []*Node
    parent *Node
}

I'm confused by the code below. It seems to me that these two parts are doing the same thing. However, One of them is wrong.

  • Correct code
cur = cur.parent
cur._insertNode(upTo, rn)
upTo, rn = cur._splitNode()
  • Code Error
cur.parent._insertNode(upTo, rn)
upTo, rn = cur.parent._splitNode()
cur = cur.parent

Can anyone tell me what the difference is?

What I'm looking for is an explanation on this issue. Is this a pitfall of Go pointer methods? Or a compiler error?

Solution

Suppose C is the node originally pointed to by cur, and A is the original parent of C node, assuming that a call to _insertNode will insert a new node B between A and C; so, we start here:

A
|
C

(plus other nodes, irrelevant to my point of view):

A
|
B
|
C

(plus other nodes, still irrelevant to my point).

It should be noted that before calling _insertNode, the parent of C is A; after calling _insertNode, C# The parent of ## is B.

With that in mind, here's your "correct code", along with comments explaining what it does:

// initially, cur = C

// set cur = A:
cur = cur.parent

// insert B between A and C:
cur._insertNode(upTo, rn)

// cur is still A

// split A:
upTo, rn = cur._splitNode()

This is your "error code", plus a comment explaining what it is doing:

// initially, cur = C

// insert B between A and C:
cur.parent._insertNode(upTo, rn)

// cur.parent is now B

// split B:
upTo, rn = cur.parent._splitNode()

// set cur = B:
cur = cur.parent

Did you see it?

The above is the detailed content of Pitfalls of calling method by pointer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete