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
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.