Go:数组索引超出范围的恐慌错误

huangapple go评论97阅读模式
英文:

Go: array out of index panic error

问题

我正在实现排序算法,但在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] <= x" 这一行遇到错误,错误信息是 "panic: runtime error: index out of range"

    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
 }

但我不认为交换函数是问题所在。

英文:

I am implementing sorting but keep getting the index bound error in Go language.

My code is following

 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 &lt; last_index; j++ {
           if container[j] &lt;= x {
                i += 1
                my_Swap(&amp;container[i], &amp;container[j])
           }
      }
      my_Swap(&amp;container[i+1], &amp;container[last_index])
      return i+1
 }

I am getting error in the line "if container[j] <= x" that says panic: runtime error: index out of range

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

Anybody has an idea?

my swap function is below

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

but I don't think swap is the problem.

答案1

得分: 1

你有一个拼写错误:

for j := first_index; i &lt; last_index; j++ {

应该是:

for j := first_index; j &lt; last_index; j++ {

这是一个很容易犯的错误 Go:数组索引超出范围的恐慌错误

Playground 示例

英文:

You have a typo:

for j := first_index; i &lt; last_index; j++ {

Should be:

for j := first_index; j &lt; last_index; j++ {

Easy enough mistake to make Go:数组索引超出范围的恐慌错误

Playground example

huangapple
  • 本文由 发表于 2013年8月31日 14:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/18545259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定