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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?