Answer the question
In order to leave comments, you need to log in
Index out of range why is this happening?
I'm trying to solve a problem. Tried through range via len(), hardcoded i<3 still getting "index out of range" error
package main
import (
"fmt"
)
func main() {
a:=[]int32{2,56,4}
b:=[]int32{7,56,6}
fmt.Println(compareTriplets(a,b))
}
func compareTriplets(a []int32, b []int32) []int32 {
scores:=[]int32{}
for i:= 0; i < 3; i++ {
if a[i] > b[i]{
scores[0]++
}
if a[i] < b[i]{
scores[1]++
}
}
return scores
}
Answer the question
In order to leave comments, you need to log in
This is not possible:
score - no size. Zero size. You cannot assign either to the first element, as written above (numbering from zero, so index 0 means the first element) or to subsequent ones. These elements simply do not exist.
It is necessary or explicitly specify the size before use, as Vasily Melnikov wrote , there are 2 methods.
or dynamically resize via . Specifically for your code - it is expedient throughscores = append(scores, newItem)
var scores [размер]тип
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question