1

I have a written a simple piece of code to read array in golang

func main(){
  var n int
  fmt.Scanf("%d", &n)
  var arr [200] int

  for i := 0; i < n; i++ {
    fmt.Printf("\nEnter %d:", i)
    fmt.Scanf("%d", arr[i])
  }

}

It is generating below output:

go run array_input.go 
5

Enter 0:1

Enter 1:
Enter 2:2

Enter 3:
Enter 4:4

Here when I enter value for array location 0, it automatically jumps to array location 2 without taking any value for array location 1. I am not able to understand why it is happening.

Thanks

Paritosh Singh
  • 6,288
  • 5
  • 37
  • 56

1 Answers1

4

You should add '&' before arr[i]

func main(){
  var n int
  fmt.Scanf("%d", &n)
  var arr [200] int

  for i := 0; i < n; i++ {
    fmt.Printf("\nEnter %d:", i)
    fmt.Scanf("%d", &arr[i])
  }

}
azisuazusa
  • 317
  • 1
  • 12
  • Thanks, it worked.But why we need to add & before array element as it represent poisition of memory only. – Paritosh Singh Aug 02 '17 at 04:56
  • '&' operator was used in the function to store the user inputted value in the address of arr https://stackoverflow.com/a/3440480/8284461 – azisuazusa Aug 02 '17 at 05:30