英文:
How to define a pointer in go, then pass this pointer in to a func to change its value?
问题
import "fmt"
func zeroptr(ptr *int) {
    *ptr = 0
}
func main() {
    var oneptr *int
    *oneptr = 1
    fmt.Println("ptr is:", *oneptr)
    zeroptr(oneptr)
    fmt.Println("after calling zeroptr, the value of ptr is:", *oneptr)
}
这段代码是不起作用的,我期望的输出如下:
ptr is: 1
调用 zeroptr 后,ptr 的值为: 0
英文:
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
答案1
得分: 1
你应该将一个int指针传递给zeroptr函数,就像这个例子中所示:
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("调用zeroptr后,ptr的值为:", ptr)
}
输出结果:
ptr is: 1
调用zeroptr后,ptr的值为: 0
你可以在golang book的"What's the point of having pointers in Go?"中找到类似的例子。
英文:
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.
答案2
得分: 0
你的指针指向什么?为了操作指针所指向的内存,你首先需要将指针指向某个地方。现在,你的ptr指向了无效的nil。你可以这样做:
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)
}
将来,请在提交代码之前对其进行缩进。你可以使用gofmt程序来实现。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论