dongyi1111 2013-11-04 18:39
浏览 26
已采纳

通过结构指针定义结构

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
", &s, s.age)

    sp := &s
    fmt.Printf("%p : %g
", &sp, sp.age)

    sp.age = 51
    fmt.Printf("%p : %g
", &sp, sp.age) // yield 51
    fmt.Printf("%p : %g
", &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条回答 默认 最新

  • dongpi3237 2013-11-04 18:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog