1

Lets say we have an int array "arr" of size 5 then &arr points to whole array of 5 int.

But when I do like &arr[-1] I don't get any error, Can somebody explain what does this means.

int arr[5] = {1, 2, 3, 4, 5};
std::cout << &arr << std::endl; // 0x61fea0
std::cout << &arr[-1] << std::endl; // 0x61fe9c (0x4 less than previous)
  • 1
    Array indexing is not bounds checked in C++. `&arr[-1]` (which is the same as `arr-1`) will compile, but that pointer value is invalid and any attempt to use it will result in undefined behavior. – dxiv Dec 08 '20 at 05:25
  • It's undefined behavior. Anything can happen, including this. – paddy Dec 08 '20 at 05:25
  • @dxiv _&arr[-1] (which is the same as arr-1)_ they aren't really the same, `arr-1` doesn't cause UB due to it doesn't subscripts. – fas Dec 08 '20 at 05:38
  • 2
    @fas They *are* the same pretty much by definition, and that includes UBs. See for example [Why is out-of-bounds pointer arithmetic undefined behaviour?](https://stackoverflow.com/questions/10473573/why-is-out-of-bounds-pointer-arithmetic-undefined-behaviour). – dxiv Dec 08 '20 at 05:42

1 Answers1

1

This is because of the relationship that arrays and pointers share. A negative index might still point at an address within the bounds and won't result in an error

Maharshi
  • 106
  • 1
  • 9
  • Okay, But what pointer arithmetic is going over here. –  Dec 08 '20 at 05:28
  • arr-1 which is perfectly legal in pointer arithmetic – geebert Dec 08 '20 at 05:31
  • 2
    @vectorX The subscript operator `a[n]` is [defined](https://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_subscript_operator) as `*(a+n)`, so `&a[n]` is `&(*(a+n)) == a+n`. This holds true for all integer `n`, so in particular `&a[-1] == a-1`. – dxiv Dec 08 '20 at 05:34
  • hmm. @dxiv, I think I got right explanation. –  Dec 08 '20 at 05:37