Easy Tutorial
❮ Go Functions Go Data Types ❯

Go Language Pointer Arrays

Go Pointers

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

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

In some cases, we might need to save arrays, which is where pointers come in handy.

The following declares an array of integer pointers:

var ptr [MAX]*int;

ptr is an array of integer pointers. Thus, each element points to a value. The following example stores three integers 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 is:

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

Go Pointers

❮ Go Functions Go Data Types ❯