问题描述
我看,你不能做对指针位掩码,为什么你不能做
在指针位操作?
I read that you can't do bitmasks on pointers, how come you can't dobitwise operations on pointers?
有什么办法来达到同样的效果呢?
Is there any way to achieve the same effect?
做同样适用于C ++?
Does the same apply to C++?
推荐答案
你不能做到按位指针操作的原因是因为标准说,你不能。我想,为什么标准是这么说的原因是因为按位指针操作将几乎普遍导致未定义或(最好)实现定义的行为。所以,就什么也没有,你可以这样做,既有用的和的便携,的像不像除了简单的操作。
The reason you can't do bitwise pointer operations is because the standard says you can't. I suppose the reason why the standard says so is because bitwise pointer operations would almost universally result in undefined or (at best) implementation-defined behavior. So there would be nothing you could do that is both useful and portable, unlike simpler operations like addition.
但你可以避开它拥有铸造:
But you can get around it with casting:
#include <stdint.h>
void *ptr1;
// Find page start
void *ptr2 = (void *) ((uintptr_t) ptr1 & ~(uintptr_t) 0xfff)
至于C ++,只需使用 reinter pret_cast
而不是C风格的转换。
这篇关于你为什么不能做用C指针位运算,以及是否有办法解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!