Go Language Pointer Arrays

Go Pointer

Before we understand pointer arrays, let's look at an example that defines 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 output of the above code execution is:

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

There is a situation where we may need to save arrays, so we need to use pointers.

The following declares an integer pointer array:

var ptr [MAX]*int;

ptr is an integer pointer array. Therefore each element points to a value. The three integers in 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 integer addresses to pointer array */
   }

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

The output of the above code execution is:

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

Go Pointer

other extensions