doushi3322 2018-06-14 06:25
浏览 6
已采纳

指针变量何时更改其地址?

Consider the following example and notice how the location of pointer variable a remains fixed, as expected:

var a *int

v1 := 1
v2 := 2

a = &v1
fmt.Printf("%p
", &a) // output: 0x1040c128
a = &v2
fmt.Printf("%p
", &a) // output: 0x1040c128

Now consider the following struct definition:

type foo struct {
    bar int
}

If a is declared as a pointer variable to foo as in this example, its location in memory does not remain fixed.

var a *foo

v1 := foo{bar: 1}
v2 := foo{bar: 2}

a = &v1
fmt.Printf("%p
", a) // output: 0x10414020
a = &v2
fmt.Printf("%p
", a) // output: 0x10414024

Why is that?

  • 写回答

1条回答 默认 最新

  • dongmi1864 2018-06-14 06:35
    关注

    Are you sure you just didn't make a typo and used fmt.Printf("%p ", a) instead of fmt.Printf("%p ", &a) because the first one uses &a and your second example uses a.

    Long answer:

    With

    fmt.Printf("%p
    ", a)
    

    you're printing out the value of a which is of type *foo which is a pointer. Roughly speaking a pointer is a variable holding an address of a memory location. With

     a = &v1
    

    you set a to the address of v1

     a = &v2
    

    you set a to the address of v2. v1 and v2 have different locations in memory and thus you when you print the value of a you'll see exactly that.

    If you use

    var a *foo
    
    v1 := foo{bar: 1}
    v2 := foo{bar: 2}
    
    a = &v1
    fmt.Printf("%p
    ", &a)
    a = &v2
    fmt.Printf("%p
    ", &a)
    

    then you'll see the same number printed twice because now you're printing out the location of a. So:

    a = &v
    fmt.Printf("%p
    ", a) // prints location of v, not location of a
    
    a = &v
    fmt.Printf("%p
    ", &a) // prints location of a, not location of v
    

    Remark:

    There's some ambiguity as to what people call a pointer and what an address. Some say that a pointer is an address because it contains an "address of a memory location" but a pointer is not actually a memory address depending on the exact context. Also, a points to b usually means that a is a pointer containing the address of b. Likewise, &v is either referred to as "the address of v" and "a pointer to v" which (at least in my opinion) are equally correct which is why I originally used "set a to a pointer to v".

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大