Go language pointer array


Release date:2023-09-16 Update date:2023-10-13 Editor:admin View counts:244

Label:

Go language pointer array

Before we look at the pointer array, let’s take a 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 as follows:

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

In one case, we may need to save the array so that 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. Three integers for the following examples are stored in an array of pointers:

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] /* Assigning an integer address to a 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 as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).