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

标签 arrays pointers indexing go

目标:我一直在使用 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) 返回类型 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/

相关文章:

mysql - MyISAM表与group by一起计数时非常慢

elasticsearch - ElasticSearch创建具有动态属性的索引

java - 随机数不在限制范围内

arrays - 快速将字符串更改为变量

c++ - 如果指针是一个函数 arguemente 并且正在通过引用传递值,我应该删除它吗?

c - 当转换 const 指针时,c 中的 const 限定符是否被保留?

c++ - 允许通过子集的迭代和随机选择进行更改的数据结构 (C++)

javascript - 将对象从数组 A 移动到数组 B. Ramda.js

安卓文字大小

mysql - 在 MySQL 中使用字符串枚举 - 性能问题