gpt4 book ai didi

pointers - 指针变量的地址何时更改?

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:36 25 4
gpt4 key购买 nike

考虑 the following example并注意指针变量 a 的位置如何保持固定,如预期的那样:

var a *int

v1 := 1
v2 := 2

a = &v1
fmt.Printf("%p\n", &a) // output: 0x1040c128
a = &v2
fmt.Printf("%p\n", &a) // output: 0x1040c128

现在考虑以下结构定义:

type foo struct {
bar int
}

如果 a 被声明为指向 foo 的指针变量,如 this example ,它在内存中的位置不会保持不变。

var a *foo

v1 := foo{bar: 1}
v2 := foo{bar: 2}

a = &v1
fmt.Printf("%p\n", a) // output: 0x10414020
a = &v2
fmt.Printf("%p\n", a) // output: 0x10414024

这是为什么?

最佳答案

你确定你只是没有打错字并使用 fmt.Printf("%p\n", a) 而不是 fmt.Printf("%p\n ", &a) 因为第一个使用 &a 而您的第二个示例使用 a

长答案:

fmt.Printf("%p\n", a)

你正在打印 a 的值,它是 *foo 类型的指针。粗略地说,指针是一个保存内存位置地址的变量。与

 a = &v1

你将 a 设置为 v1 的地址

 a = &v2

您将 a 设置为 v2 的地址。 v1v2 在内存中有不同的位置,因此当您打印 a 的值时,您会准确地看到这一点。

如果你使用

var a *foo

v1 := foo{bar: 1}
v2 := foo{bar: 2}

a = &v1
fmt.Printf("%p\n", &a)
a = &v2
fmt.Printf("%p\n", &a)

然后您会看到相同的数字被打印了两次,因为现在您正在打印 a 的位置。所以:

a = &v
fmt.Printf("%p\n", a) // prints location of v, not location of a

a = &v
fmt.Printf("%p\n", &a) // prints location of a, not location of v

备注:

对于人们所说的指针和地址,存在一些歧义。有人说指针是地址,因为它包含“内存位置的地址”,但指针实际上不是内存地址,具体取决于具体上下文。另外,a指向b通常意味着a是一个包含b地址的指针。同样,&v 被称为“v 的地址”和“指向 v 的指针”(至少在我看来)同样正确,这就是为什么我最初使用“set a to a”指向 v"的指针。

关于pointers - 指针变量的地址何时更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com