I am a beginner in C++ and I am having a hard time understanding why we use [ ] dealing with pointers that point to arrays.
As far as I know new int[5]
returns a pointer that points to an array of size 5.
So if we were to store this pointer in a variable we would do: int *arr = new int[5]
.
What I am not understanding is: if I want to access index 0 of that array, I would do arr[0]
.
Why is this syntax correct? Because in my mind arr
is a pointer, so I would have to dereference the pointer in order to access the array.
Why don't we have to dereference the pointer?
In my mind I would do something like (*arr)[0]
, but that is incorrect.
The array subscript operator []
dereferences a pointer implicitly.
This is spelled out in section 8.2.1p1 of the C++17 standard:
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
And section 6.5.2.1p2 of the C11 standard:
The definition of the subscript operator
[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
So given your example, arr[0]
is exactly the same as *(arr + 0)
. The value between the brackets is added to the pointer value to point to the desired array element and the resulting pointer is dereferenced to get the object.
Also, it's not quite correct to say your example points to an array, but rather it points to the first element of an array. A pointer to an array would look like this:
int arr[5];
int (*p)[5] = &arr;
One other thing that may be confusing is the fact that an array, in most contexts, decays to a pointer to its first element. This means you can do this:
int arr[5];
int *p = arr;
arr[1] = 5; // sets element 1 of arr
p[1] = 7; // also sets element 1 of arr