无效*地址的int *值

问题描述 投票:1回答:1

所以,我搞砸了指针,我对某些事情感到困惑。首先,让我从一个基本示例开始,其行为类似于预期:

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++ pointers casting
1个回答
2
投票

您对运算符的优先级有疑问。在所有运算符中,使用的优先级最高的是强制转换为(int*)。因此,当您执行(int*)h+1时,实际上是在执行((int*)h)+1,这不是指向第二个字节的指针,而是指向第二个integer的指针,也就是说,您正在前进sizeof(int)字节。

*(int*)h+1类似,您实际上正在做(*(int*)h)+1,也就是说,您正在读取第一个整数(即0),然后向该整数加1(0 + 1 = 1)。在这种情况下,您不执行指针算术。

[如果您想进行适当的指针算术,则需要一些括号,但是请注意,您不能随便用void *进行指针算术:改为使用char *

© www.soinside.com 2019 - 2024. All rights reserved.