doujin8476 2018-06-14 15:10
浏览 120

为什么指针会产生错误“无效的间接”?

p is a pointer which points to array arr, we can get array arr by using *p, but why can not get second element by using *p[2]?

It will cause an error :

invalid indirect of p[1] (type int)

The following code:

arr := [4]int{1,2,3,4}
var p *[4]int = &arr
fmt.Println(p)     // output &[1 2 3 4]
fmt.Println(*p)    // output [1 2 3 4]
fmt.Println(p[1])  // output 2
fmt.Println(*p[1]) //generate an error:invalid indirect of p[1] (type int)
  • 写回答

1条回答 默认 最新

  • dregduc63699 2018-06-14 15:11
    关注

    Because *p[1] means *(p[1]). And (p[1]) is an int which you can't dereference.

    Use parenthesis to dereference the pointer first, and index the result:

    fmt.Println((*p)[1])
    

    Also note that p[1] without parenthesis and dereferencing is allowed and works because p is a pointer to an array, and quoting from Spec: Index expressions:

    For a of pointer to array type:

    • a[x] is shorthand for (*a)[x]

    But note that the same is not allowed for pointer to slice types.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度