Reputation: 2884
I have some experience in C and I am totally new to golang.
func learnArraySlice() {
intarr := [5]int{12, 34, 55, 66, 43}
slice := intarr[:]
fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
fmt.Printf("address of slice 0x%x add of Arr 0x%x \n", &slice, &intarr)
}
Now in golang slice is a reference of array which contains the pointer to an array len of slice and cap of slice but this slice will also be allocated in memory and i want to print the address of that memory. But unable to do that.
Upvotes: 33
Views: 43738
Reputation: 11
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
intArr := [5]int{1, 2, 3, 4, 5}
intSlice := intArr[:]
fmt.Printf("slice addr= %p, len= %d, cap= %d\n", &intSlice, len(intArr), cap(intArr))
fmt.Printf("array addr= %p, len= %d, cap= %d\n", &intArr, len(intArr), cap(intArr))
fmt.Printf("slice first elem addr=%p\n", &intSlice[0])
fmt.Printf("backend array of slice addr=%p\n", intSlice)
fmt.Printf("backend array of slice addr=%#v\n", *((*reflect.SliceHeader)(unsafe.Pointer(&intSlice))))
}
output:
slice addr= 0xc0000a4018, len= 5, cap= 5
array addr= 0xc0000b6000, len= 5, cap= 5
slice first elem addr=0xc0000b6000
backend array of slice addr=0xc0000b6000
backend array of slice addr=reflect.SliceHeader{Data:0xc0000b6000, Len:5, Cap:5}
Upvotes: 1
Reputation: 42413
Slices and their elements are addressable:
s := make([]int, 10)
fmt.Printf("Addr of first element: %p\n", &s[0])
fmt.Printf("Addr of slice itself: %p\n", &s)
Upvotes: 18
Reputation: 166569
For the addresses of the slice underlying array and the array (they are the same in your example),
package main
import "fmt"
func main() {
intarr := [5]int{12, 34, 55, 66, 43}
slice := intarr[:]
fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
fmt.Printf("address of slice %p add of Arr %p\n", &slice[0], &intarr)
}
Output:
the len is 5 and cap is 5
address of slice 0x1052f2c0 add of Arr 0x1052f2c0
Upvotes: 5
Reputation: 1996
fmt.Printf("address of slice %p add of Arr %p \n", &slice, &intarr)
%p
will print the address.
Upvotes: 53