Pointer of array issue in go

I think pointer is the memory address (hexademic value) of a variable, when I print the pointer of an array the output is &[1, 2, 3] not as I expected. what’s I missing here?

package main

import "fmt"

func main(){
	var a = [3]int{1, 2, 3}
	var p = &a

here is output:

[1 2 3]
&[1 2 3]
&[1 2 3]
[1 2 3]

and when I try fmt.Println(*p[1]) I get error invalid indirect of p[1] (type int). If I change it to fmt.Println(*p[1]) then it works as expected. so what's the issue with*p[1]`?


1 Like

i found similar issue https://github.com/golang/tour/issues/226 check it. i think its the same thing let me know if you find better solution :slight_smile:

1 Like

You want the address beeing printed? Then you’ll need to use fmt.Printf() and the %p as format specifier for the pointer.


*p[1] is evaluate as an array of pointers in position 1 and you are meaning a pointer to an array.
Go evalues this expresion as *(p[1]), so you have to write something like
Go gives you a shortcut, so you only need to write p[1] … :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.