如何在go中定义一个指针,然后将该指针传递给func来更改其值?

问题描述:

import "fmt"

func zeroptr(ptr *int) {
    *ptr = 0
}

func main() {
    oneptr * int
    *ptr = 1
    fmt.Println("ptr is :", *ptr)
    zeroptr(ptr)
    fmt.Println("after calling zeroptr, the value of ptr is :", *ptr)
}

This does not work, I am looking for output as follows:

ptr is :1

after calling zeroptr, the value of ptr is : 0

  import“ fmt” 
 
func zeroptr(ptr * int){
 * ptr = 0  
} 
 
func main(){
 oneptr * int 
 * ptr = 1 
 fmt.Println(“ ptr is:”,* ptr)
 zeroptr(ptr)
 fmt.Println(“ 调用zeroptr之后,ptr的值为:“,* ptr)
} 
  code>  pre> 
 
 

,这不起作用,我正在寻找如下输出: p>

ptr为:1 p>

调用zeroptr后,ptr的值为:0 p> div>

What does your pointer point to? In order to manipulate the memory a pointer points to, you first need to point the pointer somewhere. Right now, your ptr is pointing to nil which is invalid. You could for instance do this:

func main() {
    var foo int
    var oneptr *int = &foo
    *oneptr = 1
    fmt.Println("oneptr is :", *oneptr)
    zeroptr(oneptr)
    fmt.Println("after calling zeroptr, the value of oneptr is :", *ptr)
}

For the future, please indent your code before submitting it here. You can do this with the gofmt program.

You should use pass an &int to zeroptr, as in this example:

package main

import "fmt"

func zeroptr(ptr *int) {
    *ptr = 0
}

func main() {

    var ptr int
    ptr = 1
    fmt.Println("ptr is :", ptr)
    zeroptr(&ptr)
    fmt.Println("after calling zeroptr, the value of ptr is :", ptr)
}

Output:

ptr is : 1
after calling zeroptr, the value of ptr is : 0

You can see a similar example in "What's the point of having pointers in Go?", from the golang book.