切片地址问题

Greg_han 2018-11-21 01:58:53
s1 := []int{1, 2, 3}
fmt.Printf("&s1=%p\n",&s1)
fmt.Printf("&s1[0]=%p\n",&s1[0])



输出:
&s1=0xc00000a0c0
&s1[0]=0xc000016408

为什s1的地址与s1[0]不同?
...全文
151 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
natpan 2018-11-23
  • 打赏
  • 举报
回复
package main import ( "fmt" ) func main() { s1 := []int{1, 2, 3} fmt.Printf("&s1=%p\n", &s1) fmt.Printf("&s1[0]=%p\n", &s1[0]) s2 := s1[:2] s3 := s1 fmt.Println("s2:=S1[:2]") fmt.Printf("&s2=%p\n", &s2) fmt.Printf("&s3=%p\n", &s3) fmt.Printf("&s2[0]=%p\n", &s2[0]) fmt.Printf("&s3[0]=%p\n", &s3[0]) fmt.Println("###typ:") fmt.Printf("s1 type is:%T\n", s1) fmt.Printf("s1[0] type is %T\n", s1[0]) fmt.Printf("s2 type is:%T\n", s2) fmt.Printf("s2[0] type is %T\n", s2[0]) } ######### &s1=0xc42000a060 &s1[0]=0xc420012180 s2:=S1[:2] &s2=0xc42000a080 &s3=0xc42000a0a0 &s2[0]=0xc420012180 &s3[0]=0xc420012180 ###typ: s1 type is:[]int s1[0] type is int s2 type is:[]int s2[0] type is int ### &s1 是 slice的地址 &s1[0] 才是slice中元素的地址。即 slice定义中的指针 array 。 type slice struct { array unsafe.Pointer len int cap int }
床上等您 2018-11-21
  • 打赏
  • 举报
回复
go语言不同于c语言
c:数组指针就是0索引的指针地址

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧