理解指针

时间:2013-12-12 17:33:54

标签: pointers go

我希望这段代码产生4个地址,每个节点2个地址,因此,有2个相同的地址,然后另一组2个相同的地址:

type node struct {
    identifier string
    parent     *node
    children   []*node
    root       int
}

func visitNodes(root *node) {   
    for i := 0; i < len(root.children); i++ {
        fmt.Printf("Visiting node %s\n", &root.children[i])
        printNodeAddress(root.children[i])
    }
}

func printNodeAddress(node *node) {
    fmt.Println(&node)
}


func main() {
    root := new(node)
    node1 := new(node)
    node2 := new(node)

    root.children = append(root.children, node1)
    root.children = append(root.children, node2)

    visitNodes(root)
}

产地:

Visiting node  %!s(**main.node=0x10500170)
0x10500180
Visiting node  %!s(**main.node=0x10500174)
0x10500190

虽然我期待它会产生这样的东西:

Visiting node  %!s(**main.node=0x10500170)
0x10500170
Visiting node  %!s(**main.node=0x10500174)
0x10500174

我是否误解了指针的基本原理,或者在处理切片时有所不同?

1 个答案:

答案 0 :(得分:5)

问题在于您正在获取指针的地址:

func printNodeAddress(node *node) {
    fmt.Println(&node) // there's now a second layer of indirection in here. a **node
}

当你真正想要看到的是指针的内存地址时。您应该将Printf更改为此:

fmt.Printf("Visiting node %p\n", root.children[i])

你的printNodeAddress功能:

fmt.Printf("%p\n", node)

然后你会得到这个:

Visiting node 0x1052f2c0
0x1052f2c0
Visiting node 0x1052f2e0
0x1052f2e0