全局变量、局部变量,局部数组变量的存储地址增长方向测试
全局变量存储在静态变量区,地址按变量定义先后顺序依次增大。
main中定义变量存储在栈区,地址按变量定义先后顺序依次增大。
局部变量存储在栈区,地址按变量定义先后顺序依次减小。
#include <iostream>
using namespace std;
int a[5];//定义的全局变量
int i;
void print();
int main()
{
int e1,e2;//
int b[5];//main中定义的数值变量
int e3,e4;//
cout << "The address of global array variable:" << '\n';
for(i=0;i<5;i++)
{
cout << &a[i] << '\n';
}
cout << "The address of the array variable defined in main:" << '\n';
for(i=0;i<5;i++)
{
cout << &b[i] << '\n';
}
cout << "The address of the variable defined in main:" << '\n';
cout << &e1 << '\n';
cout << &e2 << '\n';
cout << &e3 << '\n';
cout << &e4 << '\n';
print();
return 0;
}
void print()
{
int d1,d2;//子函数中定义的局部变量
int c[5];//子函数中定义的局部数组变量
int d3,d4;//子函数中定义的局部变量
cout << "The address of local array variable:" << '\n';
for(i=0;i<5;i++)
{
cout << &c[i] << '\n';
}
cout << "The address of local variable(c1,c2,c3,c4):" << '\n';
cout << &d1 << '\n';
cout << &d2 << '\n';
cout << &d3 << '\n';
cout << &d4 << '\n';
}
在64位win10中的32位的DEVc++上运行结果如图:
结果:
基本符合我预期推断,但是局部数组的地址增长方向在我意料之外,本以为是c[4]的地址是比c[3]的小的,但是结果能看见数组c[5]内的变量地址起始也是地址按地址一次增大的。能推断局部变量中的数组内部元素的地址也是由低到高的方向存储的。
还有意料之外是,我本以为main中定义也算全部变量,但是结果中显示在main中定义的也算局部变量,在结果中也可以看出,e1-e4的地址是依次减小的。
ps:而且能发现main中和子函数中的数据存储地址是不连续的。main中的最后定义的变量e4地址为0x------9C,而在接着运行的子函数中的第一个定义的变量d1地址是0x------6C。