doubei2340 2018-01-06 14:25
浏览 36
已采纳

我在运行以下代码时出现索引超出范围错误

i having the following code to print the indexes of an array which contains similar values.

but on running this code getting panic: indexes out of range run time error

why i am getting this

package main

import "fmt"

func main()  {
    var numbers[] int = [] int {5,2,3,5,3}
    var copy_numbers[] int
    var count [5] int
    var i,j int
    copy(copy_numbers,numbers)
    for i=0;i<len(numbers);i++ {
        for j=0;j<len(numbers) ;j++  {
            if numbers[i]==numbers[j] {
                count[i]++;
            }
        }
    }
    fmt.Printf("%d",count)

    for i=0;i<len(numbers) ;i++  {
        fmt.Println("hello")
        if count[i]>1{
            for j=0;j<len(numbers) ;j++  {
                if numbers[i]==copy_numbers[j] {

                    fmt.Printf("%d",j)

                }
            }
            fmt.Println("")
        }
    }

fmt.Printf("%d",count)

}
  • 写回答

4条回答 默认 最新

  • dongxianji0968 2018-01-06 14:37
    关注

    copy_numbers is of size 0, just as you initialized it.

    If I add the following before your first for loop:

    fmt.Println(numbers)
    fmt.Println(copy_numbers)
    

    I get:

    [5 2 3 5 3]
    []
    

    the copy builtin copies up to the length of either argument, as mentioned in the docs:

    Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

    You should initialize copy_numbers to be of the same length as numbers

      copy_numbers := make([]int, len(numbers))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于ucc28019的pfc电路中芯片一直不工作
  • ¥15 yolov8在3588板子端c++推理报错
  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能