kevinnnluo kevinnnluo - 1 year ago 67
C++ Question

Why in C++, I don't need to dereference a pointer to an array in order to access items in the array

I'm currently learning pointer. And when I create a pointer to an array with int type, I found that I can directly index the pointer without deferencing the pointer and the compiler still output exact items in my array. I do not understand why this works and why we don't need to first deference the pointer.

Code that without dereference

int arraySize = 5;
int* theArray = new int[arraySize];

for(int i = 0; i < 5; i++)
theArray[i] = i;

for (int i = 0; I < 5; i++)
std::cout << theArray[i] << std::endl;

And this gives me the output

output without derefercing

However, when I wrote like this:

for (int i = 0; i < 5; i++)
(*theArray)[i] = i;

My compiler says that: Error: expression must have pointer-to-object type. (I'm using Visual Studio 2013.)

Any help would be appreciated.

Answer Source

Code that without dereference

[ code ]

That's incorrect. You are most certainly dereferencing your pointer:

 theArray[i] = i;

That's a pointer dereference. The [] operator dereferences the pointer. This is equivalent to:

 *(theArray+i) = i;

As you know, adding or subtracting a value to a pointer advances or decrements the pointer, producing a new pointer value, and then the pointer gets dereferenced.


 *p = q;

is equivalent to

 p[0] = q;

The [] operator is just a shorthand for adding an offset to a pointer, and dereferencing the resulting pointer with the * operator. The end result is exactly the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download