Latest web development tutorials

Go language pointer array

Go pointer Go pointer

We understand the pointer array ago, look at the instance, defines the length of an integer array of 3:

package main

import "fmt"

const MAX int = 3

func main() {

   a := []int{10,100,200}
   var i int

   for i = 0; i < MAX; i++ {
      fmt.Printf("a[%d] = %d\n", i, a[i] )
   }
}

The output is the above code is executed:

a[0] = 10
a[1] = 100
a[2] = 200

In one case, we might want to save the array, so we need to use pointers.

The following declares an integer array of pointers:

var ptr [MAX]*int;

ptr is a pointer to an integer array. Therefore, each element points to a value. The following examples of three integers will be stored in the array of pointers:

package main

import "fmt"

const MAX int = 3

func main() {
   a := []int{10,100,200}
   var i int
   var ptr [MAX]*int;

   for  i = 0; i < MAX; i++ {
      ptr[i] = &a[i] /* 整数地址赋值给指针数组 */
   }

   for  i = 0; i < MAX; i++ {
      fmt.Printf("a[%d] = %d\n", i,*ptr[i] )
   }
}

The output is the above code is executed:

a[0] = 10
a[1] = 100
a[2] = 200

Go pointer Go pointer