Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
kluo Avatar asked Feb 05 '23 17:02

kluo


1 Answers

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.

Also:

 *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.

like image 178
Sam Varshavchik Avatar answered Feb 08 '23 17:02

Sam Varshavchik