Parameter transfer mode of two-dimensional array in go language

Time:2021-12-3

When implementing the dynamic programming problem with go language, I was a little confused about the parameter change of the two-dimensional array. I checked the data for a while, and then achieved the purpose (in fact, I still want to know whether the slice can be two-dimensional), so record it

Look at the code~


package main
import "fmt"
//n=7
func matrixChainOrder(p []int,m *[7][7]int,s *[7][7]int,n int){
    for i:=0;i<n;i++{
    m[i][i] = 0
    }
    for l:=2;l<n;l++{
        for i:=1;i<n-l+1;i++{
        j:=i+l-1
        m[i][j] = 10000000
        for k:=i;k<=j-1;k++{
            q:=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]
                if q<m[i][j]{
                m[i][j] = q
                s[i][j] = k
                }
            }
        }
    }
   // fmt.Println(m[1][6])
}
func main(){
    p:=[]int {30,35,15,5,10,20,15}
    var  m  [7][7]int
    var  s  [7][7]int
    matrixChainOrder(p,&m,&s,7)
    fmt.Println(m[1][6])
}

Supplement: go array is passed as a function parameter

Look at the code~


func myfun(a *[]int) {
    fmt.Print(a)
    //a[0] = 5
    (*a)[0] = 5
    //fmt.Print("here", a, "\n")
}
func test() {
    a1 := 1
    b1 := 2
    var a []*int = []*int{&a1, &b1}
    fmt.Print(a)
}
func main() {
    var a []int = []int{1, 2, 3, 4}
    myfun(&a)
    fmt.Print(a)
    test()
}

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.