Paritosh Singh
Paritosh Singh

Reputation: 6404

Golang array input not working as expected

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

Upvotes: 1

Views: 353

Answers (1)

azisuazusa
azisuazusa

Reputation: 327

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])
  }

}

Upvotes: 4

Related Questions