英文:
why does assigning to pointer result in panic
问题
我有以下的代码:
type box struct {
val int
}
var p *box
这段代码是正确的:
p = &box{val: 2}
但是这段代码会导致错误:
*p = box{val: 2}
错误信息为:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x5e59d9]
为什么第二种赋值方式会导致 panic 错误?
英文:
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?
答案1
得分: 3
因为p
指向了空值(nil
),在允许解引用p
之前,你必须先分配一些内存并使p
指向它。你可以使用new
内置函数来分配内存,并将其初始化为指向类型的零值。
p = &box{val: 2}
与以下代码具有相同的结果:
p = new(box)
*p = box{val: 2}
英文:
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}
答案2
得分: 2
因为指针没有指向任何东西。它的值是null。如果它指向了某个东西,那么你可以尝试改变被指向的东西。
p = &box{val: 2}
在这个语句之前,p = nil,在这个语句之后,p = 某个内存地址。
*p = box{val: 2}
在这个语句之前,如果p = nil,你会得到一个错误,因为你试图设置一个地址的值,而这个地址存储在变量p中。它基本上试图从空地址获取某些东西。
如果你这样做:
p = &box{val: 2}
*p = 一些新值
它会正常工作,因为p已经指向某个地址,你可以改变那个地址上的值。
英文:
Because the pointer is not pointing anything. It's value is null. If it pointed to something, then you could try to change the thing which is being pointed at.
p = &box{val: 2}
Before this statement, p = nil, after this statement, p = some memory address.
*p = box{val: 2}
Before this statement, if p = nil, you'll get an error, because you're trying to set value, of address which is stored in variable p. It basically tries to get something from nil address.
If you did that:
p = &box{val: 2}
*p = some new value
It would work fine, because p already points to some address and you can change value on that address.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论