Skip to content

疑问-【不能将函数内的指向局部变量的指针作为返回值, 函数结束指向空间会被释放】 #7

Description

@newhoo

关于这点【不能将函数内的指向局部变量的指针作为返回值, 函数结束指向空间会被释放】有疑问,示例如下:

package main

import (
	"fmt"
)

func f() *int {
	n := 100
	fmt.Println("1:", &n, n)
	return &n
}

func main() {
	n := f()
	fmt.Println("2:", n, *n)
	(*n) = 99
	fmt.Println("3:", n, *n)
}

输出:

1: 0x140000aa008 100
2: 0x140000aa008 100
3: 0x140000aa008 99

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions