全局区存放的有:
全局变量
静态变量
常量:const修饰的全局变量以及常量
#include <iostream>
using namespace std;
//全局变量
int g_b=1;
int g_a = 1;
//const修饰的全局变量,全局常量
const int c_g_a = 1;
int main()
{
//局部变量
int b = 1;
//const修饰的局部变量
const int c_a = 8;
//静态变量
static int s_c;
cout << "局部变量的地址" << (int)&b << endl;
cout << "const修饰的局部变量" << (int)&c_a << endl;
//字符串常量的地址
cout << "字符串常量的地址:" << (int)"pro" << endl;
cout << "全局变量的地址:" << (int)&g_b << endl;
cout << "全局变量的地址:" << (int)&g_a << endl;
cout << "const修饰的全局变量" << (int)&c_g_a<<endl;
cout << "静态变量的地址:" << (int)&s_c << endl;
system("pause");
return 0;
}
代码区:
1、存放cpu执行的机器命令;
2、代码区是共享的;
3、代码区是只读的;
栈区:
存放函数的参数值、局部变量等
注:不要返回局部变量的地址,栈区开放的数据由编译器自动释放
#include <iostream>
using namespace std;
int* func()
{
int a = 10;
return &a;
}
int main()
{
int* b = func();
cout << *b << endl;
cout << *b << endl;
cout << *b << endl;
system("pause");
return 0;
}
堆区:
程序结束时由操作系统回收
在C++中主要利用new在堆区开辟内存
#include <iostream>
using namespace std;
int* func()
{
//利用new关键字可以将数据开辟到堆区
//指针 本质上也是局部变量,放在栈上,指针保存的数据放在堆区
int* b = new int(10);
return b;
}
int main()
{
//在堆区开辟数据
int* p = func();
cout << *p << endl;
cout << *p << endl;
system("pause");
return 0;
}