码迷,mamicode.com
首页 > 其他好文 > 详细

Go: using a pointer to array

时间:2014-10-28 00:21:40      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   div   

下面的不是指针指向数组,而是指针指向Slice

I‘m having a little play with google‘s Go language, and I‘ve run into something which is fairly basic in C but doesn‘t seem to be covered in the documentation I‘ve seen so far.

When I pass a pointer to an array to a function, I presumed we‘d have some way to access it as follows:

func conv(x []int, xlen int, h []int, hlen int, y *[]int)

    for i := 0; i<xlen; i++ {
        for j := 0; j<hlen; j++ {
            *y[i+j] += x[i]*h[j]
        }
    }
 }

 

But the Go compiler doesn‘t like this:

sean@spray:~/dev$ 8g broke.go
broke.go:8: invalid operation: y[i + j] (index of type *[]int)

Fair enough - it was just a guess. I have got a fairly straightforward workaround:

func conv(x []int, xlen int, h []int, hlen int, y_ *[]int) {
    y := *y_

    for i := 0; i<xlen; i++ {
        for j := 0; j<hlen; j++ {
            y[i+j] += x[i]*h[j]
        }
    }
}

But surely there‘s a better way. The annoying thing is that googling for info on Go isn‘t very useful as all sorts of C\C++\unrelated results appear for most search terms.

下面是解决方案:

the semicolon and the asterisk are added and removed.

*y[i+j] += x[i]*h[j]
-->
(*y)[i+j] += x[i] * h[j];

 

Go: using a pointer to array

标签:style   blog   io   color   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/ghgyj/p/4055410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!