使用指向数组的指针

我正在尝试使用Google的Go语言,并且遇到了C语言中相当基本的东西,但到目前为止我看过的文档中似乎都没有涉及到


当我将指向某个切片的指针传递给函数时,我认为我们可以通过以下方式来访问它:


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]

        }

    }

 }

但是Go编译器不喜欢这样:


sean@spray:~/dev$ 8g broke.go

broke.go:8: invalid operation: y[i + j] (index of type *[]int)

足够公平-这只是一个猜测。我有一个相当简单的解决方法:


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]

        }

    }

}

但是,肯定有更好的方法。令人讨厌的是,在Go上搜索信息不是很有用,因为大多数搜索字词都会出现各种C / C ++ /无关的结果。


不负相思意
浏览 196回答 3
3回答

四季花海

具有Empty的类型[],例如[]int实际上是切片,而不是数组。在Go中,数组的大小是该类型的一部分,因此要真正拥有一个数组,您需要具有[16]int,而指向的指针将是*[16]int。因此,您实际上已经在使用切片,而指向切片的指针*[]int则是不必要的,因为切片已经通过引用传递了。例子:package mainimport "fmt"func sumPointerToArray(a *[8]int) (sum int) {&nbsp; &nbsp; for _, value := range *a { sum += value }&nbsp; &nbsp; return}func sumSlice (a []int) (sum int) {&nbsp; &nbsp; for _, value := range a { sum += value }&nbsp; &nbsp; return}func main() {&nbsp; &nbsp; array := [...]int{ 1, 2, 3, 4, 5, 6, 7, 8 }&nbsp; &nbsp; slice := []int{ 1, 2, 3, 4 }&nbsp; &nbsp; fmt.Printf("sum arrray via pointer: %d\n", sumPointerToArray(&array))&nbsp; &nbsp; fmt.Printf("sum slice: %d\n", sumSlice(slice))&nbsp; &nbsp; slice = array[0:]&nbsp; &nbsp; fmt.Printf("sum array as slice: %d\n", sumSlice(slice))}编辑:自首次发布以来,已更新以反映Go中的更改。

潇潇雨雨

长度是数组类型的一部分,您可以通过len()内置函数来获取数组的长度。因此,您无需传递xlen,hlen参数。在Go中,将数组传递给函数时,几乎总是可以使用slice。在这种情况下,您不需要指针。实际上,您无需传递y参数。这是C输出数组的方式。在Go风格中:func conv(x, h []int) []int {&nbsp; &nbsp; y := make([]int, len(x)+len(h))&nbsp; &nbsp; for i, v := range x {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for j, u := range h {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y[i+j] = v * u&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; return y}调用函数:conv(x[0:], h[0:])
打开App,查看更多内容
随时随地看视频慕课网APP