WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Array of pointers

Before we understand the pointer array, look at an example and define an integer array of length 3:

example

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 above code execution output is:

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

There is a situation where we might need to save the array so we need to use the pointer.

The following declares an array of integer pointers:

var ptr [MAX]*int;

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

example

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] /* Assign an integer address to an array of pointers*/
   }

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

The above code execution output is:

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