I can't fill my last array element


(Alexey K.) #1

Hi all!
I’m newby in Golang.
I met a strange things when I try fill my array like that:

package main
import "fmt"
func main() {
	var i int
	var err error
	var num[10] int
	err = nil
	for err == nil {
		_, err = fmt.Scan(&num[i])
		i++
	}
    		fmt.Println(num)
}

so, I pass 9 numbers 1 2 3 4 5 6 7 8 9 in stdin and got array

[1 2 3 4 5 6 7 8 9 0]

So, it’s ok, but my last value is still 0
When I try pass ten numbers 1 2 3 4 5 6 7 8 9 10, I’ve got:

panic: runtime error: index out of range

goroutine 1 [running]:
main.main()
	/sandbox/main.go:9 +0x177

Please somebody len me know, why I can’t do that with my last value num[9]?


(Yamil Bracho) #2

You are in a infinite loop and no boundary check s are done. When you declare your array of 10, then index goes from 0 to 9. So change your code to

for err == nil {
	if i == 10 {
		break
	}
	fmt.Printf("element[%d=", i)
	_, err = fmt.Scan(&num[i])
	i++
}

Or better:

func main() {
   var num [10]int
   for i := 0; i < 10; i++ {
    fmt.Printf("element[%d]=", i)
    fmt.Scan(&num[i])
   }
    fmt.Println(num)
}

(Alexey K.) #3

Thank you for your replay.
I see that your code will work well. but I do not understand why my code is working for array lenth-1 values in stdin? Why last num[9] cant be filled in that way? really index goes from 0 to 9 , so it is 10 values! but i can put in stdin ONLY 9!
you can check that by yorself.
if I put only one or nine digits, it works fine! but. if I try fill full array, it is get me error.
I just try understand why.
Thaks for advice!


(Yamil Bracho) #4

When “i” reaches 9 you can enter the element number 10 and then “i” increments and got value 10. Then you try to read num[10] and your programs panics because the array indexes are 0 to 9.

Please try this

var tenp
_, err = fmt.Scan(&temp)
num[i] = temp
		i++

Now it will panic in line num[i] = temp because i exceeds the limits of your array


(Alexey K.) #5

Thanks for your help! Now I see that:

 package main
 import "fmt"
 func main() {
  var i int
  var err error
  var num[10] int
  err = nil
    for err == nil {
    _, err = fmt.Scan(&num[i])
    fmt.Println("now i=",i)
    fmt.Println("now element of i=", num[i])
    fmt.Println("and error now is: ",err)
    fmt.Println("")
	i++

    
}
    fmt.Println(num)
}

RESULT:

now i= 0
now element of i= 1
and error now is:

now i= 1
now element of i= 2
and error now is:

now i= 2
now element of i= 3
and error now is:

now i= 3
now element of i= 4
and error now is:

now i= 4
now element of i= 5
and error now is:

now i= 5
now element of i= 6
and error now is:

now i= 6
now element of i= 7
and error now is:

now i= 7
now element of i= 8
and error now is:

now i= 8
now element of i= 9
and error now is:

now i= 9
now element of i= 0
and error now is: EOF

[1 2 3 4 5 6 7 8 9 0]

So, when I get EOF, i=9 and last element get 0 value. That’s why programm try get acces to index 10, instead 9 when i put 10 numbers in stdin!