Pointer math to get the length of an array

Nope. Doing this is undefined behavior:

Be aware, the expression *(&a + 1) results in undefined behavior:

...

If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

C 2011 Online Draft, 6.5.6/9

So attempting to dereference something out of bounds will result in undefined behavior. No exceptions.


Edit: I might be wrong. There is a another source on this issue saying that you are able to dereference it (emphasis mine):

[Note: for instance, the address one past the end of an array (5.7) would be considered to point to an unrelated object of the array’s element type that might be located at that address. —end note ]

Which seems to me to imply that yes, you can legally dereference it, but the result of reading or writing to the location is unspecified.

So, because it is the 1 past pointer, (according to this author) it is okay to dereference it, just not read or write. In this case, this won't affect you since you are using it for its size properties.

Though, keep in mind, anything more than 1 after the end (as opposed to the beginning) and this won't work.


Actually, this is disputed, possibly even by the committee itself. Though I should not that the question linked here is slightly different than this one.