Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language Pointer Arrays

Go Language Pointer Arrays

Go PointersGo Pointers

Before we look at pointer arrays, let's see 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 is:

a[0] = 10

a[1] = 100

a[2] = 200

In some situations, we may need to store an array, which is when we need to use pointers.

The following declares an array of integer pointers:

var ptr [MAX]*int;

ptr is an array of integer pointers. 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 the 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 PointersGo Pointers