My code:
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
s := make([][]int, n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}
s1 := 0
s2 := 0
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
s1 += s[i][j]
}
if i+j == n-1 {
s2 += s[i][j]
}
}
fmt.Println(s1 - s2)
}
}
Output:
panic: runtime error: index out of range
I tried but get panic. I want to know proper solution to this problem.
This line:
s := make([][]int, n)
Creates a slice of slices, a slice whose elements are of type []int
. It creates a slice with n
elements, but the elements of the outer slice are initialized with the zero value of the element type, and zero value of type []int
is nil
(just like for any slice type).
You get index out of range
panic because any element of the outer slice s
has zero length (because they are not initialized to a non-nil
slice), so s[i][j]
panics for any j
value.
If you want to assign elements to the "inner" slices, you also have to initialize them:
for i := 0; i < n; i++ {
s[i] = make([]int, n) // YOU ARE MISSING THIS LINE
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}