Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

go - What causes panic: runtime error: index out of range [4] with length 4 even though array is initialized as dynamic array

I have initialized a dynamic array but it shows index out of range. I have tried giving fixed length also, but it also shows the same error. Error Description : panic: runtime error: index out of range [4] with length 4

package main
import "fmt"
func missingNumber(nums []int) int {
arrSum := 0
arrLen := len(nums) + 1
for i := 0; i < arrLen; i++ {
arrSum += nums[i]
}
numSum := arrLen * (arrLen + 1) / 2
missingNumber := numSum - arrSum
return missingNumber
}
func main() {
nums := []int{1, 3, 4, 5}
result := missingNumber(nums)
fmt.Println(result)
}
question from:https://stackoverflow.com/questions/65516830/what-causes-panic-runtime-error-index-out-of-range-4-with-length-4-even-thou

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you should change arrLen := len(nums) + 1 to arrLen := len(nums).

Your array length is 4. the indexes are 0,1,2,3 for this. but when you tried to do arrLen := len(nums) + 1 . the arrlen value is now 5. but you have only 4 element. and from your loop you are trying to get a element that is not present in array. that will give you a runtime error and it will panic.

this one will work for you:

package main
import "fmt"
func missingNumber(nums []int) int {
arrSum := 0
arrLen := len(nums)
for i := 0; i < arrLen; i++ {
arrSum += nums[i]
}
m := arrLen + 1
numSum := m * (m + 1) / 2
missingNumber := numSum - arrSum
return missingNumber
}
func main() {
nums := []int{1, 3, 4, 5}
result := missingNumber(nums)
fmt.Println(result)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...