1

I've noticed in golang that we can use a pointer to an array as follows:

arr := [3]int{1, 2, 3}
var ptr *[3]int = &arr

To get value stored at an index n we can do (*ptr)[n], but why does ptr[n] also fetch me the value, Shouldn't it output some random address ?

Context

In C++, this is the observed behaviour


int (*ptr)[5];
int arr[] = {1,2,3,4,5};

ptr = &arr;
cout <<"ptr[1] = " << ptr[1] <<endl; //Outputs an address (base address of array + 20bytes)
cout << "(*ptr)[1] = " << (*ptr)[1]<< endl; //Outputs 2
2
  • 1
    In C++ there is array-to-pointer decay (implicit conversion from values of array type to values of pointer type), but no the same conversion in Go. Commented Oct 17, 2021 at 10:55
  • 1
    Go deliberately omits all the horrible things you can do to yourself with pointers in C and C++. The result is that you can't accidentally shoot yourself in the foot (C), or accidentally create numerous instances of yourself and shoot all of them in the foot (C++). See also www-users.cs.york.ac.uk/susan/joke/foot.htm Commented Oct 17, 2021 at 12:59

1 Answer 1

3

For a of pointer to array type:

  • a[x] is shorthand for (*a)[x]

See language spec: Index Expressions.

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

Comments

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.