gpt4 book ai didi

matrix - 二维数组超出范围

转载 作者:IT王子 更新时间:2023-10-29 01:59:55 26 4
gpt4 key购买 nike

我尝试构建一个二维数组。我的代码编译但执行失败并出现此错误:

Create Matrice with heigth of 10 and width of 10
Area length = 10, Area cap = 10
Loop 0
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
Loop 7
Loop 8
Loop 9
panic: runtime error: index out of range

这是我的代码,创建方法,构建一个数组数组,就像 go doc 显示的那样。 :

// matrice project matrice.go
package matrice

import (
"fmt"
)

type TwoDimensionnalMatrice struct {
col, row int
area [][]int
}

func (m TwoDimensionnalMatrice) Create(x, y int) {
m.col = x
m.row = y
fmt.Printf("Create Matrice with heigth of %d and width of %d\n", x, y)
m.area = make([][]int, m.col)
fmt.Printf("Area length = %d, Area cap = %d\n", len(m.area), cap(m.area))
for i := range m.area {
fmt.Printf("Loop %d\n", i)
m.area[i] = make([]int, m.row, m.row)
}
}

func (m TwoDimensionnalMatrice) Get(row, col int) int {
return m.area[row][col]
}

以及调用它的代码:

package main

import (
"fmt"
"matrice"
)

func main() {
mat := matrice.TwoDimensionnalMatrice{}
mat.Create(10, 10)
fmt.Printf("%d", mat.Get(5, 5))
}

最佳答案

Create() 的接收器是一个值而不是指针,这意味着您正在改变 mat 的副本在你的主要功能而不是mat本身。

改变:

func (m TwoDimensionnalMatrice) Create(x, y int)

到:

func (m *TwoDimensionnalMatrice) Create(x, y int)

或者更可能的是,您想要 matrice 中的函数返回一个新矩阵而不是初始化现有矩阵:

func New(x, y int) (*TwoDimensionnalMatrice, error) {
... create a matrix, initialize it, then return it.
}

关于matrix - 二维数组超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25095633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com