如何正确打印内存中变量的地址?

joh*_*doe 2 c++ memory windows ollydbg

我试图了解c或c ++结构如何存储在内存中。

我用C ++写了一个小程序,然后编译并运行到调试器中。我使用带有%p和&variable的printf来打印地址,但是打印出的地址和内存中的实际地址完全不同。实际上,打印的地址甚至无效。

任何想法我怎么能正确打印变量或结构的真实地址?

谢谢

这是我编写的程序的源代码:

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <conio.h>

#define XXX __asm__("nop");

int main(){
    XXX;
    XXX;
    const char *short_string = "this is a short string";
    const wchar_t *long_string = L"this is a long string";
    int a = 2;
    int b = 3;
    int c = a + b;
    int *pointer_to_a = &a;

    std::cout << "the address of short_string is: " << &short_string << std::endl;
    std::cout << "the address of long_string is: " << &long_string << std::endl;
    std::cout << "the address of a is: " << &a << std::endl;
    std::cout << "the address of a is: " << pointer_to_a << std::endl;
    std::cout << a << "+" << b << "=" << c << std::endl;
    std::cout << std::endl;
    XXX;
    XXX;
    getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是编译程序的输出: 编译程序

这是变量在内存中的位置: 调试器输出

小智 7

要打印字符串的位置,您需要:std :: cout <<(void *)short_string;

在您的示例中,您将您的本地变量的地址写在堆栈中