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?
An array is a pointer, and you can store that pointer into any pointer variable of the correct type.
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.
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 .
The C++ language allows you to perform integer addition or subtraction operations on pointers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With