You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
程序在内存中存储它的值,每个内存块(或字)有一个地址,通常用十六进制数表示,如:`0x6b0820` 或 `0xf84001d7f0`。
|
|
|
|
|
Go 语言的取地址符是 `&`,放到一个变量前使用就会返回相应变量的内存地址。
|
|
|
|
|
```go
|
|
|
|
|
a := 5
|
|
|
|
|
println(a, &a)
|
|
|
|
|
//输出为
|
|
|
|
|
5 0x14000044720
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
申明指针变量,然后使用intP=&a,表示intP指向a;intP 存储了 a 的内存地址;它指向了 a 的位置,它引用了变量 a。
|
|
|
|
|
```go
|
|
|
|
|
var intP *int
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
当一个指针被定义后没有分配到任何变量时,它的值为 `nil`,一个指针变量通常缩写为 `ptr`
|
|
|
|
|
|
|
|
|
|
看个例子:
|
|
|
|
|
```go
|
|
|
|
|
package main
|
|
|
|
|
import "fmt"
|
|
|
|
|
func main() {
|
|
|
|
|
var i1 = 5
|
|
|
|
|
fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1)
|
|
|
|
|
var intP *int
|
|
|
|
|
intP = &i1
|
|
|
|
|
fmt.Printf("The value at memory location %p is %d\n", intP, *intP)
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
输出为:
|
|
|
|
|
```text
|
|
|
|
|
An integer: 5, its location in memory: 0x24f0820
|
|
|
|
|
The value at memory location 0x24f0820 is 5
|
|
|
|
|
```
|
|
|
|
|
![[Pasted image 20231202172947.png]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
当intP = &i1时,i1的内存地址指向intP(指针变量),因此打印intP就是i1的地址,而`*intP`将得到这个指针指向地址上所存储的值;这被称为反引用(或者内容或者间接引用)操作符;另一种说法是指针转移。注:`对指针变量使用*将得到具体的值`
|