2

How do I get the address of an array element in Go?

9
  • the memory address or the index? Commented Sep 8, 2014 at 18:42
  • the memory address. what in C would be the array address + index Commented Sep 8, 2014 at 18:43
  • See golang.org/doc/faq#no_pointer_arithmetic Commented Sep 8, 2014 at 18:49
  • I doubt you can add extra characters to an array. An array has fixed size. Commented 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. Commented Sep 8, 2014 at 18:50

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.