首页 > 解决方案 > 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 吗?据我所知,通过向指针添加值,它会以字节为单位增加内存。那么,我在这里缺少什么吗?

标签: c++pointerscasting

解决方案


您对运算符的优先级有疑问。在您使用的所有运算符中,优先级最高的是强制转换为(int*). 所以当你这样做时,(int*)h+1你实际上是在做((int*)h)+1,那不是指向第二个字节的指针,而是指向第二个整数的指针,也就是说你正在推进sizeof(int)字节。

*(int*)h+1与您实际上正在做的类似(*(int*)h)+1,即您正在读取第一个整数(即0)并将该整数加 1(0 + 1 = 1)。在这种情况下,您没有进行指针运算。

如果你想做正确的指针算术,你需要一些括号,但请注意,你不能用void *: 代替可移植地做指针算术char *


推荐阅读