开发者

Getting a past-the-end pointer [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

const int n = ...;
T a[n];
T* begin = &a[0]; //or just a
T* end = begin + n;

I know this is legal and fine. However I am wondering if the following is undefined behavior or is legal as well. D开发者_StackOverflowoes the answer depend on type T?

T* end = &a[n];

P.S. This question is a curiosity question, so please refrain from mentioning that vector is a better alternative to arrays and the like :)


Yes. It is undefined behavior. No, the type of T doesn't matter.

The accepted answer in the linked duplicate is in error by its very own selection of standard citations. Unfortunately he muddles logic at the end to come up with exactly the opposite conclusion. The note in 3.9.2/3 is contained within a paragraph that is quite clearly talking about the type, not the ability to dereference. The type of the pointer (array+size) is the same "as-if" there was a valid object of type T there; this does not mean that there IS a valid object there and in fact there isn't.

There is a citation in the duplicate of the C99 standard that clearly states that &array[index] will not result in a pointer dereference that is normally implied by array[index]. C99 is not C++ though and I've not seen any equivalent text that says the same thing. It is only by that rule that it is legal in C.

C++0x will contain some of C99, I don't know if this bit is included. You should not consider them the same language.

Most C++ compilers will happily eat it up but you could always run into a compliant compiler that does not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜