无效操作:*int golang 类型的索引

Invalid operation: index of type *int golang

Objective: 我一直在使用 Go 解决 'Cracking the Coding interview' 书中的第 6 题。

请注意,我不想为这个问题提供帮助或解决方案

给定一张由 NxN 矩阵表示的图像,其中图像中的每个像素为 4 bytes,写一个方法把图片旋转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) returns 类型为 int,其他所有内容都在 'N - col - 1' 的值中,类型为 int 那么我如何获得类型 *int index?

代码:

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,这会影响您的切片。

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)
    }
}

您正在创建一个新的局部变量 b,它是行中的指针,然后出现错误:

b := &b[col][N - row - 1]