结构体的指针地址

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年10月26日 21:25:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/74208598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定