问题描述
- 堆、栈的地址高低? 栈的增长方向?
-
程序员的自我修养》说栈的地址比堆高,栈是向下增长的,堆是向上增长的。
#include
#include
int main()
{
using namespace std;
double a0[4] = {1.2 2.4 3.6 4.8};
double a1[4] = {1.2 2.4 3.6 4.8};
vector a2(4);
vector a3(4);
a2[0] = 1.0/3.0;
a2[1] = 1.0/5.0;
a2[2] = 1.0/7.0;
a2[3] = 1.0/9.0;
a3[0] = 1.0/3.0;
a3[1] = 1.0/5.0;
a3[2] = 1.0/7.0;
a3[3] = 1.0/9.0;
cout << ""a0[2]: "" << a0[2] << "" at "" << &a0[2] << endl;
cout << ""a1[2]: "" << a1[2] << "" at "" << &a1[2] << endl;
cout << ""a1[3]: "" << a1[3] << "" at "" << &a1[3] << endl;
cout << ""a2[2]: "" << a2[2] << "" at "" << &a2[2] << endl;
cout << ""a2[3]: "" << a2[3] << "" at "" << &a2[3] << endl;
cout << ""a3[2]: "" << a3[2] << "" at "" << &a3[2] << endl;
cout << ""a3[3]: "" << a3[3] << "" at "" << &a3[3] << endl;return 0;
}运行结果不是这样的,
有问题如下
堆的地址怎么比栈高?(a2[2]比a1[2]高)
数组里怎么a1[3]比a1[2]高?
解决方案
解决方案二:
地址都是由低到高,但是栈中存放的地址是由高到低。所以是反向的。
解决方案三:
只说总的栈地址高,但栈地址之间是向下的,堆是向高扩展
解决方案四:
char p= malloc (10);
printf(""%d""(char)&p-p);
free(p);
堆 内存 ,是用来动态分配的内存
栈内存,用于参数传递,函数返回地址暂存,函数参数,自动变量的内存,某些临时变量,以及运行中保存的数据的内存。
解决方案五:
char p= (char)malloc (10);
printf(""p = %p&p = %pp-&p=%p
""p&pp-(char*)&p);
free(p);