Invalid memory address or null pointer reference in Go

Asked 2 years ago, Updated 2 years ago, 100 views

If you execute the code below,
panic:runtime error:invalid memory address or null pointer reference occurs.
I think this is because the *Node Left returned by Insert() is nil, but
How do I prevent Node.Left from becoming nil?


package main

type Node structure {
    Value int
    Left, Right, Parent* Node
}

func(n*Node)Insert(numint)*Node{

    if num>n.Value {
        n.Left.Value=num
        n.Left.Parent=n
    } else if num<n.Value {
        n.Right.Value=num
        n.Right.Parent=n
    }
    return n
}

funcmain(){
    root:=&Node {Value:1264523}
    root.Insert (22222)
}



go

2022-09-30 21:12

1 Answers

Just as the main function substitutes the Node type structure (pointer to ) for the root variable, you should assign the Node type structure to n.Left and n.Right.

 func(n*Node) Insert(numint)*Node{
    if num>n.Value {
        n.Left=&Node {Value:num, Parent:n}
    } else if num<n.Value {
        n.Right=&Node {Value:num, Parent:n}
    }
    return n
}

However, if there are already n.left or n.right nodes before inserting a new Node type structure, you may need to "replace nodes."


2022-09-30 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.