tags:

views:

152

answers:

3

why pointer is more efficient or superior than declaring array?

+5  A: 

You're comparing apples to oranges.

A pointer holds a value which is the address of another variable. An array is a contiguous collection of items. They aren't the same.

If you clarify your question, we could give you a better answer. As it stands, it's pretty meaningless.

GMan
A: 

In my testing (a few years back) I found the exact opposite - an array reference was faster than a pointer. I think this was with MSVC 6.0. It all depends on the assembly code the compiler decides to generate, and it's quite arbitrary.

To clarify, I was comparing something like the following:

for (int i = 0;  i < length;  ++i)
    sum += p[i];

for (int i = 0;  i < length;  ++i)
    sum += *p++;
Mark Ransom
+1  A: 

They aren't. According to the C standard, a[x] is just syntactic sugar for *(a+x). In fact, modern processors can produce sometimes faster code if a[x] is used instead of raw pointer arithmetic as some static analyses can compute more information in this case, enabling more aggressive optimizations. The reason is the easier alias analysis.

swegi