0

I am working with tutorials point.com example.

int  var[MAX] = {10, 100, 200};
int  *ptr;

// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--)
{
    cout << "Address of var[" << i << "] = ";
    cout << ptr << endl;

    cout << "Value of var[" << i << "] = ";
    cout << *ptr << endl;

    // point to the previous location
    ptr--;
}
return 0;

So, why &var[MAX - 1] and why not &var[MAX]? If we do not use a reference, would it be possible to solve this problem in a different manner?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Richard Rublev
  • 6,495
  • 12
  • 58
  • 100

1 Answers1

6

Because arrays in C++ are zero-based, i.e. start from 0 and end at n-1. var[MAX] is the element past the end of the array, so is out-of-bounds and accessing it is undefined behaviour.

var   { 10, 100, 200 }
index   ^0  ^1^  ^2^   ^3?
TartanLlama
  • 61,102
  • 13
  • 147
  • 188
  • not *accessing* it, but [you **can** have a pointer to it](http://stackoverflow.com/a/988220/2297448) as long as you don't dereference it. – RamblingMad Jul 13 '15 at 11:13