Why is the address size different? (0x206a10 – 0x104382e0)

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

Why is the address size different? (0x206a10 - 0x104382e0)

问题

以下是代码的翻译结果:

var p1 = new(int)
var p2 *int = new(int)
var p3 = 0
var p4 *int

func main() {
    fmt.Println(*p1, &p1, p1)
    fmt.Println()
    fmt.Println(*p2, &p2, p2)
    fmt.Println()
    fmt.Println(p3, &p3)
    fmt.Println()
    fmt.Println(p4, &p4)
}

输出结果:

0 0x206a10 0x104382e0

0 0x206a14 0x104382f0

0 0x21ccc0

<nil> 0x206a18

英文:

http://play.golang.org/p/BgnHN-GikU

var p1 = new(int)
var p2 *int = new(int)
var p3 = 0
var p4 *int

func main() {
	fmt.Println(*p1, &amp;p1, p1)
	fmt.Println()
	fmt.Println(*p2, &amp;p2, p2)
	fmt.Println()
	fmt.Println(p3, &amp;p3)
	fmt.Println()
	fmt.Println(p4, &amp;p4)
}

0 0x206a10 0x104382e0

0 0x206a14 0x104382f0

0 0x21ccc0

&lt;nil&gt; 0x206a18

答案1

得分: 6

不同的是十六进制表示的长度,而不是地址的大小。

在Go Playground上打印的所有地址都是4个字节,但如果前几个字节(或位)为零,则不会打印出来。

此外,如果你仔细观察,全局变量的地址有6个十六进制数字,而由new()分配和返回的指针有8个十六进制数字。这是因为那些由new()返回的int在堆上分配,具有更大的偏移量(因此具有“更大”的内存地址)。

例如:

var i, j int32 = 123, 123000
fmt.Printf("%x %x\n", i, j)

即使这两个数字都是4个字节长(32位),输出结果是7b 1e078。你可以使用格式化字符串添加填充的0,像这样:

fmt.Printf("%08x %08x\n", i, j)

这将得到0000007b 0001e078,但即使ij的长度“小于”4个字节(例如int16),这种填充也会始终填充到8个数字,因此这种填充不能告诉你它们的大小是否不同。

英文:

It's not the address size what is different, it's the size (length) of the hexadecimal representation as you printed it.

All addresses you print on the Go Playground are 4 bytes, but if the first bytes (or bits) are zero, they are not printed.

Also if you take a closer look, addresses of your global vars have 6 hexa digits, pointers allocated and returned by new() have 8 hexa digits. This is because those ints (returned by new()) are allocated on the heap with bigger offset (and thus "bigger" memory address).

For example:

var i, j int32 = 123, 123000
fmt.Printf(&quot;%x %x\n&quot;, i, j)

Prints 7b 1e078 even though both numbers are 4 bytes long (32 bits). You may use a format string to add padding 0s like this:

fmt.Printf(&quot;%08x %08x\n&quot;, i, j)

Which results in 0000007b 0001e078 but this will always pad to 8 digits even if i or j would be "less" than 4 bytes (e.g. int16), so this padding won't tell you if they are of different sizes.

huangapple
  • 本文由 发表于 2016年1月26日 11:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/35006766.html
匿名

发表评论

匿名网友

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

确定