doufei1988 2017-07-21 21:54
浏览 54
已采纳

为什么分配给指针会导致恐慌

I have the following code:

type box struct {
    val int
}

var p *box

This works fine:

p = &box{val: 2}

But this results in error:

*p = box{val: 2}

Error:

panic: runtime error: invalid memory address or nil pointer dereference 
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x5e59d9]

Why does the 2nd form of assignment result in panic?

  • 写回答

2条回答 默认 最新

  • donglian1953 2017-07-22 09:35
    关注

    Because p points to nothing (nil). You must first allocate some memory and make p point to it before being allowed to deference p. You can use the new builtin to allocate memory initialised to the zero value of the pointed type.

    p = &box{val: 2}
    

    has the same result as:

    p = new(box)
    *p = box{val: 2}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致