英文:
defining struc by struct pointer
问题
我无法理解为什么在使用结构体指针(&s)定义结构体(sp)之后,修改后者(sp)时,初始结构体(s)仍然被修改。
代码中定义了一个名为person的结构体,包含name和age两个字段。
在main函数中,首先创建了一个名为s的结构体实例,name字段为"Sean",age字段为50。然后使用fmt.Printf函数打印了s的内存地址和age字段的值。
接下来,创建了一个名为sp的结构体指针,指向s。再次使用fmt.Printf函数打印了sp的内存地址和age字段的值。
然后,将sp的age字段修改为51,并使用fmt.Printf函数分别打印了sp和s的内存地址和age字段的值。
输出结果显示,sp的内存地址在修改前后保持不变,age字段的值从50变为51。而sp指向的结构体s的内存地址也保持不变,但age字段的值也变为了51,而不是50。
对于C语言家族、Go语言和指针,我还是新手,所以如果能给出正确的概念或错误指导,我将非常感谢!提前谢谢!
英文:
I can't understand why after defining a struct (sp) with a struct pointer (&s), the initial struct (s) keeps being modified while mutating the latter (sp).
http://play.golang.org/p/TdcL_QJqfB
type person struct {
name string
age int
}
func main() {
s := person{name: "Sean", age: 50}
fmt.Printf("%p : %g\n", &s, s.age)
sp := &s
fmt.Printf("%p : %g\n", &sp, sp.age)
sp.age = 51
fmt.Printf("%p : %g\n", &sp, sp.age) // yield 51
fmt.Printf("%p : %g\n", &s, s.age) // yields 51, but why not 50 ???
}
Output:
0xc0100360a0 : %!g(int=50)
0xc010000000 : %!g(int=50)
0xc010000000 : %!g(int=51)
0xc0100360a0 : %!g(int=51) // why not 50 ???
I'm new to C family language, Go and pointers, so any pointer (
) to the right concept or error would be very kind of you. thanks in advance !
答案1
得分: 4
你有一个对象s。还有一个指针sp,它指向s。所以当你通过sp设置age时,实际上是修改了s。
记住,sp不是一个独立的对象。它就像一个别名。
英文:
You have an object s. And a pointer sp that points to s. So when you set age through sp, you're actually modifying s.
Remember, sp is not a separate object. It's like an alias.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论