dp6319 2016-11-13 16:03
浏览 53
已采纳

不同类型的指针有什么区别?

A pointer references a location in memory. Actually all memory addresses have the same type independently of the variable type as far as I understand.

Instead of using different pointer type (*int, *string etc..), is this possible using only one type (var p pointer) for all the pointer types?

What is the difference between different pointer types?

package main

import "fmt"

func main() {
    i := 5
    s := "abc"

    var pi *int      // alternatively var pi pointer
    var ps *string   // alternatively var ps pointer 

    pi = &i
    ps = &s

    fmt.Printf("%p %p", pi, ps)  // result is 0x1040e0f8 0x1040a120
}
  • 写回答

2条回答 默认 最新

  • doubu8643 2016-11-14 06:21
    关注

    is this possible using only one type for all the pointer types?

    Yes, that is pretty much how C works. Unfortunately, that makes the language dangerous. Say you have an array of 10 bytes. If you JUST pass the pointer, the other code won't know how many bytes it's safe to access. That leads to all kinds of buffer overflow errors. (i.e. HeartBleed)

    In Go, they pointer knows the type of the thing it points to, so it can prevent your code from having buffer overflow problems all the time.

    You can do what you want, but only by using the Unsafe package. As the name suggests, that is a very dangerous thing to do.

    Perhaps if you post what you are ACTUALLY trying to do, people can help you. Using unsafe pointers is not the only way to write performant code.

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

报告相同问题?

悬赏问题

  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表