How do I get the address of an array element in Go?
-
the memory address or the index?Anthony– Anthony2014-09-08 18:42:54 +00:00Commented Sep 8, 2014 at 18:42
-
the memory address. what in C would be the array address + indexealfonso– ealfonso2014-09-08 18:43:25 +00:00Commented Sep 8, 2014 at 18:43
-
See golang.org/doc/faq#no_pointer_arithmetictopskip– topskip2014-09-08 18:49:21 +00:00Commented Sep 8, 2014 at 18:49
-
I doubt you can add extra characters to an array. An array has fixed size.topskip– topskip2014-09-08 18:50:19 +00:00Commented Sep 8, 2014 at 18:50
-
I know that there's no pointer arithmetic. But I still need the address to store it in another container.ealfonso– ealfonso2014-09-08 18:50:34 +00:00Commented Sep 8, 2014 at 18:50
|
Show 4 more comments
1 Answer
Use the address operator & to take the address of an array element. Here's an example:
package main
import "fmt"
func main() {
a := [5]int{1, 2, 3, 4, 5}
p := &a[3] // p is the address of the fourth element
fmt.Println(*p)// prints 4
fmt.Println(a) // prints [1 2 3 4 5]
*p = 44 // use pointer to modify array element
fmt.Println(a) // prints [1 2 3 44 5]
}
Note that the pointer can be used to access the one element only. It's not possible to add or subtract from the pointer to access other elements.