英文:
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, &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
答案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
,但即使i
或j
的长度“小于”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 int
s (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("%x %x\n", i, j)
Prints 7b 1e078
even though both numbers are 4 bytes long (32 bits). You may use a format string to add padding 0
s like this:
fmt.Printf("%08x %08x\n", 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论