0

What happening in following code?

int main()
{
    int i = 37;
    int* pi = &i;
    i[pi];  //works
    i[0];   //error C2109: subscript requires array or pointer type
}

Why is allowed to indexing int with pointer argument and what does it do?

relaxxx
  • 7,566
  • 8
  • 37
  • 64
  • `i[pi]` is the same as `pi[i]` is the same as `*(pi + i)` – Alex Jul 01 '16 at 13:51
  • 1
    in C++, array indexing is explicitly implemented using (commutative) pointer arithmetic (along the lines of `*(pi + i)`) and it was left so that `pi[i]` and `i[pi]` behaved the same. in the second case, writing `i[reinterpret_cast(0)]` would do as you expected, i.e. undefined behavior as it dereferences a null pointer – obataku Jul 01 '16 at 13:53

1 Answers1

0

i[pi] is the same as *(i + pi).

Jarod42
  • 203,559
  • 14
  • 181
  • 302