dpeqsfx5186 2015-03-04 09:47
浏览 205
已采纳

golang从函数返回对象

I am struggling to understand exactly what is happening when you return a new object from a function in go.

I have this

func createPointerToInt() *int {
    i := new(int)
    fmt.Println(&i);
    return i;
}

func main() {
    i := createPointerToInt();
    fmt.Println(&i);
}

The values printed returned are

0x1040a128
0x1040a120

I would expect these two values to be the same. I do not understand why there is an 8 byte difference.

In what I see as the equivalent C code:

int* createPointerToInt() {
    int* i = new int;
    printf("%#08x
", i);
    return i;
}

int main() {
    int* r = createPointerToInt();
    printf("%#08x
", r);
    return 0;
}

The address returned is the same:

0x8218008
0x8218008

Am I missing something blindingly obvious here? Any clarification would be greatly appreciated!

  • 写回答

3条回答 默认 最新

  • du532861657 2015-03-04 09:50
    关注

    You are printing the address of the pointer here fmt.Println(&i);. Try this:

    func main() {
        i := createPointerToInt();
        fmt.Println(i); //--> Remove the ampersand
    }
    

    i is the pointer returned from createPointerToInt - while &i is the address of the pointer you are trying to print. Note in your C sample you are printing it correctly:

    printf("%#08x
    ", r);
                     ^No ampersand here
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52