According to my class notes, you can allocate an array in C++ like
int *A = new int[5]
where A is a pointer to the array.
But then you can access the array as A[3]. Why can you do that? Isn't A a pointer and not the actual array?
According to my class notes, you can allocate an array in C++ like
int *A = new int[5]
where A is a pointer to the array.
But then you can access the array as A[3]. Why can you do that? Isn't A a pointer and not the actual array?
The indexing operator[] actually defined to work on pointers, not on arrays. A[3] is actually a synonym for *(A+3). It works on arrays as a consequence of the fact that arrays can be implicitly converted to pointers to their first element.
You are right! Basically, this is syntactic sugar, meaning that the language designers put something in place to make your life a bit easier, but behind the scenes it is doing something quite different. (This point is arguable)
Effectively, what this is doing is taking the pointer location at A, moving the pointer 5 int-sizes up, then giving you the value by dereferencing.
This is the starting point of pointer arithmetic: you can add or subtract values with pointers, as long you don't move off the array (well, you can move up to right after the array). Basically, the following hold (for A being a pointer to an array with at leat i + 1 elements:
A[i]
*(A + i) // this what A[i] means
*(i + A) // addition is commutative
i[A] // this sould work, too - and it does!