c++ - 通过指针访问时NAN是否返回false?

标签 c++ pointers nan math.h

我正在编写一个返回指向数字数组的指针的函数。为了能够使用指针遍历数字,我将最后一个元素设置为 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/

相关文章:

javascript - ajax 文本变量传递 0 或 NaN

c++ - 即使 V(U) 有效,从 std::pair<T, U> 到 std::pair<T, V> 的转换也不起作用?

c# - 将结构数组从 C#(.NET Core) 传递到 C++(unamnaged)

c++ - 如何将指针作为迭代器返回?

c++ - 由于 next_permute 而运行无限循环

c++ - 为什么 int& r = 0 是非法的,而 const int& r = 0 是合法的?

r - 零膨胀负二项式分布函数 NaN 警告

C++:关于释放内存的问题

c++ - 使用数组的段错误

c - 未定义对“sqrt”的引用