Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer comparison with []operator for arrays?

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.

like image 595
Cool_Coder Avatar asked Jan 09 '14 02:01

Cool_Coder


People also ask

What is * array [] in C?

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 [].

What does a [] mean in C?

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

What is difference between pointer to array and array of pointers?

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.

What is pointer in C compare pointers with array?

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.


2 Answers

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.

like image 93
Shoe Avatar answered Nov 06 '22 08:11

Shoe


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

  1. SO Answer
  2. Eli Bendersky's explanation
like image 30
Keeler Avatar answered Nov 06 '22 09:11

Keeler