Home > Back-end >  I have this type of error while iterate arrary in for loop "panic: runtime error: index out of
I have this type of error while iterate arrary in for loop "panic: runtime error: index out of

Time:08-17

package main
import (
    "fmt"
)
func main() {
    var a int
    var b int
    
    var ar [] int
    fmt.Scan(&a)
    
    for i:= 1; i<a; i   {
        fmt.Scan(&b)
        ar[i] = b
    }
    
    fmt.Print("Hello")
    for i:= a; i>0; i-- {
        b = ar[i]
        fmt.Print(b)
    }
}

CodePudding user response:

Corrected code, I think it's what you want

package main

import (
    "fmt"
)

func main() {
    var a int
    var b int

    fmt.Scan(&a)

    // make slice with len a, cap a, 0 filled
    ar := make([]int, a, a)
    for i := 0; i < a; i   {
        fmt.Scan(&b)
        ar[i] = b
    }

    fmt.Print("Hello")
    for i := a - 1; i >= 0; i-- {
        b = ar[i]
        fmt.Print(b)
    }
}

CodePudding user response:

for i:= 1; i<a; i   {
        fmt.Scan(&b)
        ar[i] = b
    }

ar is empty. If you want to add something, then use ar = append(ar, ...)

Or create ar with the correct size: ar = make(int[], a). Then ar will contain several zero values.

  • Related