Golang指向指针的指针(双指针)介绍

2021年3月9日16:11:47 发表评论 825 次浏览

先决条件:Go中的指针

Go编程语言中的指针或高朗是一个变量, 用于存储另一个变量的内存地址。指针是一个特殊的变量, 因此它甚至可以指向任何类型的变量。基本上, 这看起来像是一个指针链。当我们定义一个指向指针的指针时, 第一个指针用于存储第二个指针的地址。这个概念有时被称为双指针.

如何在Golang中声明指向指针的指针?

声明Pointer to Pointer类似于声明

Go中的指针

。不同之处在于我们必须另外放置一个"

*

’, 指针名称前的名称。通常, 当我们使用

var关键字

以及类型。下面的示例和图像将以更好的方式解释该概念。

范例1:在下面的程序中指针pt2存储的地址pt1指针。取消引用pt2即* pt2将给出变量的地址v或者你也可以说指针的值pt1。如果你会尝试** pt2那么这将给出变量的值v即100。

Go中的双指针
// Go program to illustrate the
// concept of the Pointer to Pointer
package main
   
import "fmt"
   
// Main Function
func main() {
   
         // taking a variable
         // of integer type
     var V int = 100
       
     // taking a pointer 
     // of integer type 
     var pt1 * int = &V
       
     // taking pointer to 
     // pointer to pt1
     // storing the address 
     // of pt1 into pt2
     var pt2 ** int = &pt1
   
     fmt.Println( "The Value of Variable V is = " , V)
     fmt.Println( "Address of variable V is = " , &V)
   
     fmt.Println( "The Value of pt1 is = " , pt1)
     fmt.Println( "Address of pt1 is = " , &pt1)
   
     fmt.Println( "The value of pt2 is = " , pt2)
   
     // Dereferencing the 
     // pointer to pointer
     fmt.Println( "Value at the address of pt2 is or *pt2 = " , *pt2)
       
     // double pointer will give the value of variable V
     fmt.Println( "*(Value at the address of pt2 is) or **pt2 = " , **pt2)
}

输出如下:

The Value of Variable V is =  100
Address of variable V is =  0x414020
The Value of pt1 is =  0x414020
Address of pt1 is =  0x40c128
The value of pt2 is =  0x40c128
Value at the address of pt2 is or *pt2 =  0x414020
*(Value at the address of pt2 is) or **pt2 =  100

范例2:让我们在上述程序中进行一些更改。通过使用取消引用更改指针的值来为指针分配一些新值, 如下所示:

指针如何工作
// Go program to illustrate the
// concept of the Pointer to Pointer
package main
  
import "fmt"
  
// Main Function
func main() {
  
     // taking a variable
     // of integer type
     var v int = 100
  
     // taking a pointer
     // of integer type
     var pt1 * int = &v
  
     // taking pointer to
     // pointer to pt1
     // storing the address
     // of pt1 into pt2
     var pt2 ** int = &pt1
  
     fmt.Println( "The Value of Variable v is = " , v)
  
     // changing the value of v by assigning
     // the new value to the pointer pt1
     *pt1 = 200
  
     fmt.Println( "Value stored in v after changing pt1 = " , v)
  
     // changing the value of v by assigning
     // the new value to the pointer pt2
     **pt2 = 300
  
     fmt.Println( "Value stored in v after changing pt2 = " , v)
}

输出如下:

The Value of Variable v is =  100
Value stored in v after changing pt1 =  200
Value stored in v after changing pt2 =  300

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: