【问题标题】:Go: array out of index panic errorGo:数组超出索引恐慌错误
【发布时间】:2013-09-03 21:53:49
【问题描述】:

我正在实现排序,但在 Go 语言中不断收到索引绑定错误。

我的代码如下

 func My_Partition(container []int, first_index int, last_index int) int {
      var x int = container[last_index]
      i := first_index - 1

      for j := first_index; i < last_index; j++ {
           if container[j] <= x {
                i += 1
                my_Swap(&container[i], &container[j])
           }
      }
      my_Swap(&container[i+1], &container[last_index])
      return i+1
 }

我在“if container[j]

    main.My_Partition(0x2101b20c0, 0x7, 0x7, 0x0, 0x6, ...)
/Path/main.go:34 +0xff

有人有想法吗?

我的交换功能在下面

 func my_Swap(a *int, b *int) {
      temp := *a
      *a = *b
      *b = temp
 }

但我认为交换不是问题。

【问题讨论】:

    标签: arrays sorting indexing go


    【解决方案1】:

    你有一个错字:

    for j := first_index; i < last_index; j++ {
    

    应该是:

    for j := first_index; j < last_index; j++ {
    

    容易犯的错误:-)

    Playground example

    【讨论】:

    • 非常感谢。那是一个愚蠢的错误,三个小时都想不通……谢谢!
    • @dfsadxsadqwd213 没问题,类似的事情我做过很多次了!为了将来参考,您不需要自定义交换功能。 Go 支持多重赋值,所以你可以只做container[i], container[j] = container[j], container[i] 而不需要临时变量。
    • 很好。我在 C 思维模式下编码。我应该像在 Ruby 和 Python 中那样尝试过。谢谢
    • 几年前我也犯过类似的错误,现在我尽量避免使用单字母变量。额外的打字是没有这些错误的小代价。
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多