gpt4 book ai didi

arrays - 无效操作 : index of type *int golang

转载 作者:IT王子 更新时间:2023-10-29 02:34:05 28 4
gpt4 key购买 nike

目标:我一直在使用 Go 解决“Cracking the Coding interview”一书中的第 6 题。

注意我不想帮助或解决这个问题

给定一张由 NxN 矩阵表示的图像,其中图像中的每个像素为 4bytes,写一个方法把图片旋转90度。你能就地做到这一点吗?

问题:我创建了一个数组数组来表示矩阵,并创建了一个交换函数以顺时针交换矩阵中的元素。出于某种原因,我在尝试编译时遇到了这个非常奇怪的错误:

./Q6.go:29: invalid operation: b[N - col - 1] (index of type *int)
./Q6.go:30: invalid operation: b[N - row - 1] (index of type *int)

我从哪里得到类型 *int 作为索引?在 Go 文档中,len(v) 返回类型 int,其他所有内容都在 'N - col - 1' 的值中,类型为 int 那么我如何获得类型 *int 索引?

代码:

package main

import "fmt"

func main() {
b := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} // 4 by 4 array going from 1 to 16
N := len(b)

for row := 0; row < N / 2; row++ {
for col := row; col < N - row - 1; col++ {
a := &b[row][col]
b := &b[col][N - row - 1]
c := &b[N - col - 1][col] // <-- Error here
d := &b[N - row - 1][N - col - 1] // <-- Error here
fourSwap(a, b, c, d)
}
}

for r := range b {
for c:= range b[0] {
fmt.Print(b[r][c])
}
fmt.Print("\n")
}

}

// [a][-][-][b] [c][-][-][a]
// [-][-][-][-] --> [-][-][-][-]
// [-][-][-][-] --> [-][-][-][-]
// [c][-][-][d] [d][-][-][b]

func fourSwap(a, b, c, d *int) {
temp := *b
*b = *a
*a = *c
*c = *d
*d = temp
}

最佳答案

您在循环内声明 b,这会遮蔽您的 slice 。

for row := 0; row < N / 2; row++ {
for col := row; col < N - row - 1; col++ {
a := &b[row][col]
b := &b[col][N - row - 1] <<<< b is now an *int
c := &b[N - col - 1][col] // <-- Error here
d := &b[N - row - 1][N - col - 1] // <-- Error here
fourSwap(a, b, c, d)
}
}

关于arrays - 无效操作 : index of type *int golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981710/

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