3

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

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

知道如何正确打印变量或结构的真实地址吗?

谢谢

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

#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;
}

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

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

4

1 回答 1

8

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

在你的例子中,你写了你的局部变量的地址,它在堆栈上

于 2019-03-08T16:15:09.477 回答