标签:sign exe pre erro 声明 evel nal 写法 一个
package main import "fmt" func main() { var a int = 10 //每个变量都有两层含义,变量的内存和变量的地址 fmt.Printf("a = %d\n", a) //变量的内存 10 fmt.Printf("a = %v\n", &a) //变量的地址 0xc042060080 //保存某个变量的地址,需要指针类型, *int保存int的地址, **int保存*int的地址 //声明(定义),定义只是特殊的声明 //定义一个变量p,类型为*int var p *int p = &a fmt.Printf("p = %v, &a = %v\n", p, &a) *p = 666 //*p操作的不是p的内存,是p指向的内存(其实就是a) fmt.Printf("*p = %v, a = %v\n", *p, a) }
执行结果为
GOROOT=C:\Go #gosetup GOPATH=E:\go\develop #gosetup C:\Go\bin\go.exe build -i -o C:\Users\baylor\AppData\Local\Temp\___go_build__go.exe E:/awesomeProject01/指针的基本操作.go #gosetup "C:\Program Files\JetBrains\GoLand 2018.1.5\bin\runnerw.exe" C:\Users\baylor\AppData\Local\Temp\___go_build__go.exe #gosetup a = 10 a = 0xc042060080 p = 0xc042060080, &a = 0xc042060080 *p = 666, a = 666
注意,永远不要操作没有合法指向的内存,比如:
package main import "fmt" func main() { var p *int p = nil fmt.Printf("p = %v\n", p) *p = 666 //这个就是错误的,因为它没有正确的指向内存地址 fmt.Printf("*p = %v\n", *p) }
执行结果
GOROOT=C:\Go #gosetup GOPATH=E:\go\develop #gosetup C:\Go\bin\go.exe build -i -o C:\Users\baylor\AppData\Local\Temp\___go_build__go.exe E:/awesomeProject01/不要操作没有合法指向的内存.go #gosetup "C:\Program Files\JetBrains\GoLand 2018.1.5\bin\runnerw.exe" C:\Users\baylor\AppData\Local\Temp\___go_build__go.exe #gosetup p = <nil> panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x1 addr=0x0 pc=0x48ce1c] goroutine 1 [running]: main.main() E:/awesomeProject01/不要操作没有合法指向的内存.go:10 +0x7c
正确的写法应该是这样的
var a int p = &a *p = 666 fmt.Printf("*p = %v\n", *p)
执行结果
p = <nil>
*p = 666
标签:sign exe pre erro 声明 evel nal 写法 一个
原文地址:https://www.cnblogs.com/baylorqu/p/9534548.html