打印指针指向的内存位置和值

时间:2019-01-18 22:21:18

标签: c++

这是我的代码:

int myInt = 15;
int *myPointer;
myPointer = &myInt;

如何获取myInt的存储位置和myPointer指向的值?我会使用解引用运算符吗?

3 个答案:

答案 0 :(得分:2)

myInt的存储位置可以使用&运算符(在这种情况下,称为“引用运算符”)进行访问,将其分配给指针后,还可以打印出指针的值。

myPointer指向的值可以用*运算符(在此上下文中为“ dereference运算符”)取消引用,并且一旦将myInt的地址分配给指针,其值为myPointer指向的值。

代码段:

#include <iostream>

int main() {
    int myInt = 15;
    int *myPointer;
    myPointer = &myInt;

    std::cout << "Memory location of myInt: " << &myInt << std::endl;
    std::cout << "Value of myPointer: " << myPointer << std::endl;
    std::cout << "Value of myInt: " << myInt  << std::endl;
    std::cout << "Value pointed to by myPointer: " << *myPointer << std::endl;

    return 0;
}

输出:

Memory location of myInt: 0x7ffe724fa57c
Value of myPointer: 0x7ffe724fa57c
Value of myInt: 15
Value pointed to by myPointer: 15

答案 1 :(得分:1)

  

我如何获取myInt [...]的内存位置?

std::cout << &myInt << '\n';

std::cout << myPointer << '\n'; // becase myPointer points to myInt, so its value is exactly &myInt
  

[...]和myPointer指向的值?

std::cout << *myPointer << '\n';

*之前注意myPointer。称为取消引用

答案 2 :(得分:1)

请注意,通常,您宁可cout << static_cast<const void*>(my_pointer)打印其地址。如果您尝试打印char*的地址,则会发现<<超载。

另一个选择是printf( "%p\n", my_pointer );中的<stdio.h>