1

Usually in c++, when traversing through an array you would count up and use the index. However, I am wondering why using the array as an index works as well. For example,

#include <iostream>
using namespace std;

int main() {
    int a[] = {5,7,3,2,0};
    int i = 0;
    for(i = 0; i <5; i++)
    {
        cout<<i[a]<<"\n";
    }
    return 0;
}

The output would be the same as using a[i]. Why is this?

1 Answers1

-1

In C++, the [] operator really amount to address addition.

So when you write: a[i]

the compiler sees: *(a + i)

And conversely, when you write i[a], the compiler sees: *(i + a).

Piotr Trochim
  • 693
  • 5
  • 15
  • 7
    No, an array is not a pointer. – juanchopanza May 08 '17 at 22:24
  • It's a pointer to its first element. – Piotr Trochim May 08 '17 at 22:25
  • 1
    [I'll just leave this here](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/4810668) – JGroven May 08 '17 at 22:26
  • @PiotrTrochim No it's not. – Baum mit Augen May 08 '17 at 22:26
  • No, an array is not a pointer. So it cannot be a pointer to the first element. – juanchopanza May 08 '17 at 22:26
  • 1
    An array can *decay* to a pointer to the first element when passed over certain boundaries. But by itself, it's still an array, not a pointer. –  May 08 '17 at 22:27
  • Let me rephrase that then - the mental shortcut was too great. When one creates a C-style array (say int a[5]), then the following happens: a stack allocation of size {5 * sizeof(int)} is made, and the address to it's start is assigned to variable 'a'. Therefore - the variable 'a' becomes a pointer to the allocated area. And of course, you can do the following assignment: int* b = a; - no need for deriving the address using the '&' operator. – Piotr Trochim May 08 '17 at 22:34
  • 2
    Still wrong. Try `sizeof(a)` vs `sizeof(int*)`. – Baum mit Augen May 08 '17 at 22:38
  • My bad, and thank's for a valuable read. I must admit to always having thought of raw arrays as ... well, what I described. Thanks ! – Piotr Trochim May 08 '17 at 22:50