我已经在代码中创建了一些指针,但是结果却不是我期望的。
这是简单的代码:
int main(int argc, char const* argv[])
{
int myInt = 23;
int* ptr = &myInt;
char* buffer = new char[8];
memset(buffer, 0, 8);
char** ptr2 = &buffer;
std::cout << "ptr address is " << ptr << std::endl;
std::cout << "buffer pointer is pointing to address " << buffer << std::endl;
std::cout << "ptr2 pointer is pointing to address " << ptr2 << std::endl;
std::cout << "Dereferencing ptr2 = " << *ptr2 << std::endl;
return 0;
}
这是运行代码的结果:
我想知道为什么不显示缓冲区指针地址,为什么对
ptr2
的取消引用也没有显示任何东西,而指向缓冲区指针的指针(ptr2
)却显示该地址。这对我来说毫无意义。 最佳答案
流<<
运算符是explicitly overloaded for all kinds of char*
,可将其打印为以空字符结尾的字符串。要打印指针,您需要强制转换它:
std::cout << "buffer pointer is pointing to address " << reinterpret_cast<void*>(buffer) << std::endl;
关于c++ - 对指针及其地址感到困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58464670/