我正在编写一个返回指向数字数组的指针的函数。为了能够使用指针遍历数字,我将最后一个元素设置为 NAN
以标记数组的结尾。
我的循环类似于
for(int* it=ptr;!isnan(*it);++it)
//print *it
但它一直运行直到崩溃所以我写了一些测试代码:
int* test = new int[1];
*test = NAN;
cout << isnan(NAN) << endl;
cout << isnan(*test) << endl;
结果是:
1
0
我见过很多使用 NAN
作为数组中的“塞子”的例子。那为什么不起作用呢?
最佳答案
你有未定义的行为,因为你试图将浮点类型的 NAN
转换为 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.
由于 NAN
只是 float 的一个特殊值,将其存储在 int
中没有意义。整数类型没有特殊的非数字值。您可以使用一些特定的值来表示数组的末尾,但这不是一个特别令人愉快的解决方案。
如果您要像这样动态分配您的数组,您将不得不通过传递它来自己跟踪它的大小。对于其他数组(您实际上有一些表示数组对象本身的东西,而不仅仅是指向其元素的指针),您可以使用 std::end
找到它的结尾。但是,和往常一样,我建议改用标准容器。
关于c++ - 通过指针访问时NAN是否返回false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165640/