You have undefined behaviour because you are attempting to convert NAN
, which is of floating point type, to an int
and that value cannot be represented by an int
.
§4.9/1 [conf.fpint] A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.
Since NAN
is just a special value of floating point numbers, it doesn't make sense to store it in an int
. Integer types don't have a special not-a-number value. You could use some specific value to denote the end of the array, but that's not a particularly pleasant solution.
If you're going to dynamically allocate your array like this, you are going to have to keep track of the size of it yourself by passing it around. For other arrays (where you actually have something denoting the array object itself, rather than just a pointer to its elements), you could use std::end
to find the end of it. However, as usual, I suggest using standard containers instead.