#include<iostream>
using namespace std;
/*
1.2程序运行后
栈区
存放函数的参数、局部变量
注意:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
堆区
程序员利用new在堆区开辟内存空间
*/
int * func(int b){ // 形参存放在栈上
int a = 10; // 局部变量存放在栈上
return &a; // 该函数执行完后,栈上数据被自动释放
}
int * func_1(){
int * p1 = new int(10); // 主动在堆区开辟变量10,返回值为其地址
// 指针p1实质也是局部变量,其存放在栈区,它的值为一个地址,该地址为堆区新开辟的变量的地址,该地址存放10
return p1;
}
int main(){
// 栈区
int * p = func(100);
//cout << *p << endl;
//cout << *p << endl;
// 堆区
int * p2 = func_1();
cout << p2 << endl;
cout << *p2 << endl;
return 0;
}
