I have been reading a book which says that accessing array elements by pointer arithmetic's is much faster than the [] operator. In short this code is faster than this code. The book does not say why. Is it advisible to use such pointer arithmetic's even if it provides significant improvement in speed?
#include <iostream>
using namespace std;
int main() {
// your code goes here
double *array = new double[1000000];
for(int i = 0; i < 1000000; i++)
{
array[i] = 0;//slower?
}
delete[] array;
return 0;
}
#include <iostream>
using namespace std;
int main() {
// your code goes here
double *array = new double[1000000];
for(int i = 0; i < 1000000; i++)
{
*(array + i) = 0;//faster?
}
delete[] array;
return 0;
}
EDIT:
Quote from book pg 369, 2nd last line
The pointer accessing method is much faster than array indexing.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].
*array[] means array of pointers, in your example: char *somarray[] = {"Hello"}; somarray[] is array of char* . this array size is one and contains address to on string "Hello" like: somarray[0] -----> "Hello"
Here is a list of the differences present between Pointer to an Array and Array of Pointers. A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer.
Pointer Comparison in C In C language pointers can be compared if the two pointers are pointing to the same array. All relational operators can be used for pointer comparison, but a pointer cannot Multiplied or Divided.
No, they are exactly the same thing. I definitely suggest you to drop that book and pick another one up as soon as possible.
And even if there was any performance difference, the clarity of x[12]
over *(x + 12)
is much more important.
Array indices are just syntactic sugar for pointer arithmetic. Your compiler will boil down a[i]
into *((a) + (i))
. Agreed, run away from that book!
For more in-depth explanations, see
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