你能帮我了解变量的存储位置(堆栈、堆、静态内存)吗?我怎样才能确定它?我的意思不是凭直觉,但我想在屏幕上印一些标志什么在哪里。是否可以?
到目前为止,我试图通过打印变量的地址来查看变量的存储位置。但这并没有给我太多。你能看看,给我一个建议。如果我犯了错误(请参阅我对程序的评论),请告诉我。
#include "stdafx.h"
#include <iostream>
using namespace std;
int * p1 = new int [3]; // Static memory as it is a global array;
namespace P {int * p2 = new int[3];} // Static memory as it is a namespace;
namespace {int * p3 = new int[3];} // Static memory as it is a namespace;
using namespace P;
int _tmain(int argc, _TCHAR* argv[])
{
int * p4 = new int[3]; // Heap as there is a new operator.
static int * p5 = new int [3]; // Static memory as the variable is static.
cout << "p1: "<< p1 << endl;
cout << "p2: "<< p2 << endl;
cout << "p3: "<< p3 << endl;
cout << "p4: "<< p4 << endl;
cout << "p5: "<< p5 << endl;
cout << endl;
cout << "p5 - p4: " << p5 - p4 << endl;
cout << "p4 - p3: " << p5 - p4 << endl;
cout << "p3 - p2: " << p5 - p4 << endl;
cout << "p2 - p1: " << p5 - p4 << endl;
system("pause");
}