I do not believe this a duplicate (see below).†
I found the question that is nearly a precise duplicate, but I think the answers failed to analyze the loophole. See: Is `*((*(&array + 1)) - 1)` safe to use to get the last element of an automatic array?
I know the usual method is to compute sizeof(array)/sizeof(*array)
to get the number of elements in the array. (And it has been pointed out to me in comments that C++ has std::size(array)
.)
So, I reasoned that number could be calculated with pointer math if I could get to the address of one past the last element. But, then it occurred to me that I could:
&array + 1
But, the type of this value is pointer to array, so to allow the math to work, I would need to dereference this value.
const auto N = *(&array + 1) - array;
Is there an allowance in C and C++ that allows this dereference to be legal?
I know that you are allowed to point to one past the last element of an array, but you are not allowed to dereference it. However, this dereference yields an array object, which immediately decays to a pointer to its first element.
I could use a reinterpret_cast
to avoid using the dereference operator, but I was wondering if the the C and/or C++ languages would allow the dereference in this case.
† I missed a similar question, but this question is subtly different. I already understand how the code works, and I understand that there is normally a problem with dereferencing the pointer past the last element of the array. I am asking if the fact that array objects decay to a pointer when used in an expression allows for an exception. I think it might, because dereferencing a pointer to an object would normally result in the object value itself to be used in the expression (which would be a problem if the object does not exist).