c++ - void* 地址的 int* 值
问题描述
所以,我在搞乱指针,我对一些事情感到困惑。首先,让我从一个行为符合预期的基本示例开始:
void* h = new char[16] {}; //pointer to a array of char, 16 bytes, and initilizes with 0
int* o = (int*)h; //gets the adress of the first byte
*o = 16; //sets the value
std::cout << *(int*)h << std::endl; //Prints the memory value
std::cout << *o; //Prints the memory value
它打印这个:
16
16
但是这个并没有输出我认为的结果:
int* o = (int*)h+1; //gets the adress of the second byte
*o = 16; //sets the value
std::cout << *(int*)h+1 << std::endl; //Prints the memory value
std::cout << *o; //Prints the memory value
但它输出:
1
16
这两个数字不应该是 16 吗?据我所知,通过向指针添加值,它会以字节为单位增加内存。那么,我在这里缺少什么吗?
解决方案
您对运算符的优先级有疑问。在您使用的所有运算符中,优先级最高的是强制转换为(int*)
. 所以当你这样做时,(int*)h+1
你实际上是在做((int*)h)+1
,那不是指向第二个字节的指针,而是指向第二个整数的指针,也就是说你正在推进sizeof(int)
字节。
*(int*)h+1
与您实际上正在做的类似(*(int*)h)+1
,即您正在读取第一个整数(即0
)并将该整数加 1(0 + 1 = 1
)。在这种情况下,您没有进行指针运算。
如果你想做正确的指针算术,你需要一些括号,但请注意,你不能用void *
: 代替可移植地做指针算术char *
推荐阅读
- ios - Swift 泛型和协议:从静态函数返回专用类型?
- c# - 如何从序列化类 C# 中获取数据?
- python-3.x - 找不到满足要求的版本torch>=1.1.0(来自torchvision==0.3.0)
- css - 如何确保 HighStocks 图表 x 轴跨越整个图表宽度?
- reactjs - 为什么在 Electron 应用程序中 React Context API 行为异常?
- readline - can't read logger message thru socat -u UNIX-RECV:/dev/log,ignoreeof - 因为没有新行
- react-native - Expo Firestore上传base64不起作用
- mysql - 具有逻辑错误条件的插入防止触发器
- css - ReactJS 上边距
- java - 在应用程序/“永久”文本视图中的每个活动上显示相同的文本视图?