Home > Blockchain >  Access values inside array using pointers
Access values inside array using pointers

Time:10-18

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

CodePudding user response:

For a of pointer to array type:

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

See language spec: Index Expressions.

  • Related