两次运行的代码如下
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
while(1)
{
int a = 1;
int b = 2;
int c = 5;
int d = 3;
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
Sleep(1000);
cout << endl;
}
}
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
while(1)
{
int a = 1;
int b = 2;
int c = 5;
int d = 3;
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
//cout << &d << endl;
Sleep(1000);
cout << endl;
}
}
只是注释掉了一行
两次得到的输出结果(即变量a, b, c的地址)竟然不一样,
第一段代码运行结果:
而第二段代码运行结果为:
请问这是怎么回事,造成这个结果的原因是因为链接过程当中的重定位吗?
当变量声明的时候,计算机会用一块内存存储值,程序结束的时候释放掉。第二次运行的时候又会重新找块内存存储,两次的地址不一定会相同的
程序结束的时候释放掉,再次运行时是重新分配的。
所以就算是第一段代码,每次运行的结果都不一样,第二段也是这样。