Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between *(Pointer + Index) and Pointer[]

Tags:

c++

pointers

int* myPointer = new int[100];  // ...  int firstValue = *(myPointer + 0); int secondValue = myPointer[1]; 

Is there any functional difference between *(myPointer + index) and myPointer[index]? Which is considered better practice?

like image 585
Maxpm Avatar asked Jan 07 '11 04:01

Maxpm


People also ask

Is array [] a pointer?

An array is a pointer, and you can store that pointer into any pointer variable of the correct type.

What is the difference between pointer and pointer array?

Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.

What does * and &indicate in pointer?

The fundamental rules of pointer operators are: The * operator turns a value of type pointer to T into a variable of type T . The & operator turns a variable of type T into a value of type pointer to T .

Can pointers be indexed?

The C++ language allows you to perform integer addition or subtraction operations on pointers.


1 Answers

Functionally, they are identical.

Semantically, the pointer dereference says "Here's a thing, but I really care about the thing X spaces over", while the array access says "Here's a bunch of things, I care about the Xth one."

In most cases, I would prefer the array form.

like image 100
Mike Caron Avatar answered Sep 23 '22 03:09

Mike Caron