doucu7525 2019-06-05 20:34
浏览 73
已采纳

如何获取结构中嵌入式切片的内存地址?

How can I get the memory address of an embedded slice in a struct?

Example:

type t1 struct {
    data string
}

type t2 struct {
    listData []t1
}

Now I want to know the memory address of listData. I couldn't figure out how to get the memory address out of it using the following:

newData := t2{}
newData.listData = append(newData.listData, t1{data:"mydata"})
printf("%p", &newData.listData) // this doesn't work, in fact it returns address of newData
  • 写回答

1条回答 默认 最新

  • doulao1934 2019-06-05 20:38
    关注

    listData is the first field in the struct, its memory offset relative to the struct's address is zero, so they have the same address.

    type t2 struct {
    listData []string
    moreData []int
    }
    
    func main() {
        var foo t2
        fmt.Printf("%p %p %p", &foo, &foo.listData, &foo.moreData)
    }
    

    0x43e260 0x43e260 0x43e26c

    https://play.golang.org/p/FVMujcUHHYq

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!