[英]Please explain what is incorrect about this procedure to find the largest pointer
Wouldn't the highest pointer be the one which can't be incremented through pointer arithmetic? 最高的指针会不会是无法通过指针算法递增的指针?
#include <iostream>
int main()
{
// Find the largest pointer
int x = 0;
int* px = &x;
while ((px+1) != px)
++px;
std::cout << "The largest pointer is: " << px;
return 0;
}
yields 产量
Timeout
As already mentioned, you've got an infinite loop because the condition can never be false
. 如前所述,您有一个无限循环,因为条件永远不会为
false
。
That being said, what you're doing is undefined behaviour, illegal C++. 话虽这么说,您正在做的是未定义的行为,非法的C ++。 Pointer arithmetic is only legal with pointers pointing to the same array (and a single object is treated as an array of one element) and right past the end of it.
指针算术仅在指针指向相同数组(并且单个对象被视为一个元素的数组)并且在其末尾之后才合法。 You can't expect a reasonable outcome of your program even if you fix the loop.
即使您修复了循环,也无法期待程序的合理结果。
I suspect the value of std::numeric_limits
<
uintptr_t
>::max()
is the theoretical maximum value of pointer (converted to integer), but it might not be avaliable to your program. 我怀疑
std::numeric_limits
<
uintptr_t
>::max()
的值是指针的理论最大值(转换为整数),但是它可能不适用于您的程序。 There are things such as virtual address space and segmented memory model to consider. 需要考虑诸如虚拟地址空间和分段内存模型之类的问题 。 Anyway, exact values of pointers (except for
nullptr
) is not something you should be concerned with. 无论如何,指针的确切值(
nullptr
除外)不是您应该关注的。 You get pointers by taking addresses of existing objects or by calling allocation functions and that's that. 您可以通过获取现有对象的地址或调用分配函数来获得指针,仅此而已。
NB I think you have a misconception that attempting to increment an integer type beyond its maximum value will just do nothing. 注意:我认为您有一个误解,尝试将整数类型增加到其最大值以上将无济于事。 That's incorrect - unsigned integers will wrap around to 0 and with signed integers you get undefined behaviour again (see signed integer overflow ).
这是不正确的-无符号整数将回绕为0,使用有符号整数,您将再次获得未定义的行为(请参见有符号整数溢出 )。
Hope that helps. 希望能有所帮助。
这将永远是错误的,因此永远不会退出
while ((px+1) != px)
Look at this program: 看一下这个程序:
#include <iostream>
int main()
{
int *px = (int *) (~0);
std::cout << "Value: " << px;
++px;
std::cout << " Value: " << px << std::endl;
}
whose output is: 其输出是:
Value: 0xffffffffffffffff Value: 0x3
As you can see, when you increment a pointer that is at its maximum, it values is reseted and begins again 如您所见,当递增最大指针时,它将重置其值并再次开始
You might want to look for the largest pointer value that occurs before wrap-around, ie: 您可能想要查找在回绕之前出现的最大指针值,即:
while (px+1 > px)
px++;
...which will not work, of course, without the proper casts: ...如果没有适当的转换,那当然是行不通的:
while ((unsigned long long)(px + 1) > (unsigned long long)px)
px++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.