Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "one-past-the-end" pointer of a non-array type a valid concept in C++?

Tags:

The C++ standard [sec 5.7] says:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So, am I correct in assuming that pointers one-past-the-end of other types than arrays are undefined?

For example:

int a = 0;
vector<int> v(&a, (&a)+1);

The above snippet compiles and works just fine (with g++), but is it valid?

like image 544
Bernhard Kausler Avatar asked Jan 24 '13 16:01

Bernhard Kausler


People also ask

Can you reference past the last element in an array?

It is legal. According to the gcc documentation for C++, &array[5] is legal. In both C++ and in C you may safely address the element one past the end of an array - you will get a valid pointer.

Can a pointer point one past the end of an object?

it is possible for a pointer to an object and a pointer one past the end of a different object to hold the same address.

Can we use pointers instead of array?

Not only can a pointer store the address of a single variable, it can also store the address of cells of an array. Consider this example: int *ptr; int arr[5]; // store the address of the first // element of arr in ptr ptr = arr; Here, ptr is a pointer variable while arr is an int array.

Is an array always a pointer in C?

In simple words, array names are converted to pointers. That's the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same. There are a few cases where array names don't decay to pointers.


1 Answers

No, it is legal. 5.7(4) - one paragraph before your quote - says: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."

like image 146
JoergB Avatar answered Sep 21 '22 19:09

JoergB