2

Possible Duplicate:
Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?

In the C++ standard library, many algorithms takes the begin() and end() iterator as argument. But the trick is that the end() iterator is after the end of the container. If I want to apply algorithms to standard c-array I have to pass the equivalent of begin() and end() pointers.

The question is the following :

const unsigned int size = 10;
int array[size];
std::iota(&array[0], &array[size], 0); // <- Version 1
std::iota(&array[0], &array[0]+size, 0); // <- Version 2

Are the two versions strictly equivalent ? Can I use version 1 without any problem according to the C++ standard ?

My doubt comes from the fact that &array[size] access the element after the end of the array and then takes it address whereas &array[0]+size do not access the element after the end of the array.

Community
  • 1
  • 1
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • Why not `std::iota(array, array + size, 0);`? – Jesse Good Nov 05 '12 at 03:04
  • @Jesse: Ew, implicit conversions. ;) – Xeo Nov 05 '12 at 03:05
  • @LightnessRacesinOrbit : in your link what is the difference between a "one-past-the-end pointer" and "out of bound pointer" ? – Vincent Nov 05 '12 at 03:07
  • @Vincent: jalf said it best: "In general, you're not even allowed to create an out-of-bounds pointer. A pointer must point to an element within the array, or one past the end. Nowhere else." An out-of-bounds pointer to an array element is an invalid one. – Lightness Races in Orbit Nov 05 '12 at 03:10
  • The standard is very carefully worded to make using a one-past-the-end pointer valid for the purposes of `end()`. You are allowed to compare other pointers into the same array to it, but not allowed to dereference it in any way. Creating the pointer in the manner you do is not the same as dereferencing it. – Omnifarious Nov 05 '12 at 03:24

1 Answers1

3

Just use std::begin and std::end from <iterator> and don't worry - they'll do the right thing. :)

Xeo
  • 129,499
  • 52
  • 291
  • 397