所以,我弄乱了指针,我对一些事情感到困惑。首先,让我从一个基本示例开始,它的行为与预期相似:
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吗? 据我所知,通过向指针添加值,它会以字节为单位增加内存。那么,我在这里缺少什么吗?
运算符的优先级有问题。在您使用的所有运算符中,优先级最高的是 cast to(int*)
的优先级。所以当你做(int*)h+1
时,你实际上是在做((int*)h)+1
,这不是指向第二个字节的指针,而是指向第二个整数的指针,也就是说你正在前进sizeof(int)
字节。
类似地,*(int*)h+1
你实际上是在做(*(int*)h)+1
,也就是说你正在读取第一个整数(这将是0
(并将1加到该整数(0 + 1 = 1
(。在这种情况下,您不是在执行指针算术。
如果你想做正确的指针算术,你需要几个括号,但请注意,你不能用void *
来移植地做指针算术:使用代替char *