douzhonglong3789 2015-05-01 04:44
浏览 50
已采纳

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

Objective: I have been solving question 6 from the book 'Cracking the Coding interview' by using Go.

NOTE I DO NOT WAN'T HELP OR SOLUTIONS TO THIS QUESTION

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

Problem: I made an array of arrays to represent the matrix and I created a swap function to swap the elements clockwise in the matrix. For some reason I get this really weird error when trying to compile:

./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)

Where am I getting type *int as an index? In the Go documenation, len(v) returns type int and everything else is in the value of 'N - col - 1' is type int so how am I getting type *int index?

Code:

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

}

// [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
}
  • 写回答

2条回答 默认 最新

  • doumianfeng6979 2015-05-01 04:58
    关注

    You declare b inside the loop, and that shadows your 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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog