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

1 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked.But why we need to add & before array element as it represent poisition of memory only.
'&' operator was used in the function to store the user inputted value in the address of arr stackoverflow.com/a/3440480/8284461

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.