切片中元素的地址为什么相同?以及如何将它们复制到指针? [英] Why address of element in slice is the same? and how to copy them to a pointer?
本文介绍了切片中元素的地址为什么相同?以及如何将它们复制到指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一段代码:
//initialize a slice
arr := make([]int, 0)
arr = append(arr, 1, 2)
for _, k := range arr {
fmt.Printf("%p %+v\n", &k, k)
}
//make a copy, but the element is a pointer
arrP := make([]*int, 0)
for _, k := range arr {
arrP = append(arrP, &k)
}
//why arrP is different with arr?
for _, k := range arrP {
fmt.Printf("%p %+v\n", k, *k)
}
结果是:0xc000018088 10xc000018088 20xc000090000 20xc000090000 2
我的问题:
为什么地址相同?
为什么arrP [0]的值不为1?
the results are :
0xc000018088 1
0xc000018088 2
0xc000090000 2
0xc000090000 2
my questions:
why address is the same?
why the value of arrP[0] is not 1?
推荐答案
查看全文