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

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

Go: array out of index panic error

问题

我正在实现排序算法,但在Go语言中一直遇到索引越界错误。

我的代码如下:

  1. func My_Partition(container []int, first_index int, last_index int) int {
  2. var x int = container[last_index]
  3. i := first_index - 1
  4. for j := first_index; i < last_index; j++ {
  5. if container[j] <= x {
  6. i += 1
  7. my_Swap(&container[i], &container[j])
  8. }
  9. }
  10. my_Swap(&container[i+1], &container[last_index])
  11. return i+1
  12. }

我在第 "if container[j] <= x" 这一行遇到错误,错误信息是 "panic: runtime error: index out of range"

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

有人有什么想法吗?

我的交换函数如下:

  1. func my_Swap(a *int, b *int) {
  2. temp := *a
  3. *a = *b
  4. *b = temp
  5. }

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

英文:

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

My code is following

  1. func My_Partition(container []int, first_index int, last_index int) int {
  2. var x int = container[last_index]
  3. i := first_index - 1
  4. for j := first_index; i &lt; last_index; j++ {
  5. if container[j] &lt;= x {
  6. i += 1
  7. my_Swap(&amp;container[i], &amp;container[j])
  8. }
  9. }
  10. my_Swap(&amp;container[i+1], &amp;container[last_index])
  11. return i+1
  12. }

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

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

Anybody has an idea?

my swap function is below

  1. func my_Swap(a *int, b *int) {
  2. temp := *a
  3. *a = *b
  4. *b = temp
  5. }

but I don't think swap is the problem.

答案1

得分: 1

你有一个拼写错误:

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

应该是:

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

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

Playground 示例

英文:

You have a typo:

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

Should be:

  1. 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:

确定