dpfw3607 2018-09-08 07:07
浏览 28
已采纳

为什么在Go中无法将整数添加到“已取消引用”的指针变量中?

Coming from Python, I'm currently learning Go and trying to wrap my head around pointers.

I've written this code in order to understand the concept:

a := 1
b := &a
fmt.Println(b) // Shows the memory address of a
fmt.Println(*b) // Shows the value 1
*b++
fmt.Println(a) // Shows the value 2 (as expected)

I tried to play around with this code to improve my understanding. The following, however, does not work:

a := 1
b := &a
fmt.Println(b) // Shows the memory address of a
fmt.Println(*b) // Shows the value 1
b = *b + 1 // Compile error: invalid operation: b * +1 (mismatched types *int and int)
fmt.Println(a)

Apparently, *b is of type *int, while the value 1 is (obviously) of type int. However, why is it possible to increment the value of a with *b++in the first example?

  • 写回答

4条回答 默认 最新

  • douchen7555 2018-09-08 08:36
    关注

    From the beginning:

    b := &a

    Here, b is of type *int, a pointer to a location in memory where value of a is stored. When you do *b, you are accessing a value from the location b pointer points to.

    When you do *b++, it stands for *b = *b + 1 and you are incrementing a value on the location b pointer points to.

    b = *b + 1 is invalid because you are trying to add *b and 1, which are both type of int, to b, which is a pointer (type of *int).

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题