英文:
Pointer address of a struct
问题
考虑以下代码:
package main
import "fmt"
type S struct {
Val int
}
func main() {
e1 := S{Val: 1}
fmt.Printf("%p\n", &e1)
fmt.Printf("%p\n", &e1.Val)
}
运行代码后,我们会得到类似以下的输出:
0xc00001c030
0xc00001c030
我感到困惑的是为什么结构体指针和它的成员的地址是相同的?
Go Playground链接:https://go.dev/play/p/Wl4tnD9TFmA
英文:
Consider this code :
package main
import "fmt"
type S struct {
Val int
}
func main() {
e1 := S{Val: 1}
fmt.Printf("%p\n", &e1)
fmt.Printf("%p\n", &e1.Val)
}
After running it, we'll get something like that:
0xc00001c030
0xc00001c030
What confuses me is why pointer's address of the struct and it's member are the same?
Link to Go Playground: https://go.dev/play/p/Wl4tnD9TFmA
答案1
得分: 3
结构体是一个内存区域,其中所有字段按顺序放置(如果存在对齐,则可能存在间隔)。与数组相同。因此,结构体的第一个元素显然应该与结构体本身具有相同的地址。
英文:
Struct is memory area with all fields put there one by one (if alignment present, then they could be with gaps). Same as array. So first element of struct obviously should have same address as struct itself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论