dongpochi9741 2011-05-31 06:24 采纳率: 100%
浏览 256
已采纳

如何存储指针指向的地址?

I am trying to create a map of addresses of objects that I create with the time at which it is allocated. The key is the address returned by the call to new(). How do I get the address returned by new()?

type T struct{a, b int }

func main(){

        var t int64 = time.Nanoseconds()
        memmap := make(map[uint8]int64)
        fmt.Printf("%d
", t)
        var ptr *T = new(T)
        ptr.a = 1
        ptr.b = 2
        fmt.Printf("%d %d %p %T
", ptr.a, ptr.b, ptr, ptr)
        //memmap[ptr] = t //gives error
        //var temp uint8 = ptr//gives error
}

Please tell me what should be the type of the key field in the map so that I can store the address returned by new()? I plan to use new() with different types, get the allocated address and map it with the creation time.

  • 写回答

2条回答 默认 最新

  • doufuhuang6981 2011-05-31 07:01
    关注

    You can use the type Pointer from the unsafe package, but that is, the package name implies it, unsafe. The address itself is a opaque thing and there's only little use in actually using a address value alone for a map, better use a tuple of type and address. That's what unsafe.Reflect does provide you. The package reflect offers you the function UnsafeAddr and a lot more.

    I suggest you read the package documentation for reflect and unsafe packages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入