切片中元素的地址为什么相同?以及如何将它们复制到指针? [英] Why address of element in slice is the same? and how to copy them to a pointer?

查看:89
本文介绍了切片中元素的地址为什么相同?以及如何将它们复制到指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码:

    //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?

推荐答案

请参见

为什么地址相同?

why address is the same?

k的值随着循环的前进而更新.

The value of k is updated as the loop advances forward.

为什么arrP [0]的值不为1?

why the value of arrP[0] is not 1?

与上述相同.

以对您提供的示例进行修改后的版本进行演示:

To demonstrate with a modified-version of the example that you provided:

    arr := make([]int, 0)
    arr = append(arr, 1, 2)
    for i, _ := range arr {
        fmt.Printf("%p  %+v\n", &arr[i], arr[i])
    }

    arrP := make([]*int, 0)
    for i, _ := range arr {
        arrP = append(arrP, &arr[i])
    }

    for i, _ := range arrP {
        fmt.Printf("%p  %+v\n", arrP[i], *arrP[i])
    }

结果是:

0xc00009a010  1
0xc00009a018  2
0xc00009a010  1
0xc00009a018  2

这篇关于切片中元素的地址为什么相同?以及如何将它们复制到指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆