c++程序执行时,将内存大方向分为4个区域
代码区:存放函数体的二进制代码,由操作系统进行管理
全局区:存放全局变量和静态变量以及常量
栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
1、全局区
#include<iostream>
using namespace std;
//全局变量
int g_a = 10;
int g_b = 10;
//const修饰的全局常量
const int c_g_a = 10;
const int c_g_b = 10;
int main()
{
//全局区
//全局变量、静态变量、常量
//创建普通局部变量
int a = 10;
int b = 10;
cout << "局部变量a的地址为:" << (int)&a << endl;
cout << "局部变量b的地址为:" << (int)&b << endl;
cout << "全局变量g_a的地址为:" << (int)&g_a << endl;
cout << "全局变量g_b的地址为:" << (int)&g_b << endl;
//静态变量
static int s_a = 10;
static int s_b = 10;
cout << "静态变量s_a的地址为:" << (int)&s_a << endl;
cout << "静态变量s_b的地址为:" << (int)&s_b << endl;
//常量
//字符串常量
cout << "字符串常量的地址为:" <<(int) &("hello word") << endl;
//const修饰的变量
//const修饰的全局变量,const修饰的局部变量
cout << "const修饰的全局常量c_g_a的地址为:" << (int)&c_g_a << endl;
cout << "caonst修饰的全局常量c_g_b的地址为:" << (int)&c_g_b << endl;
const int c_l_a = 10;
const int c_l_b = 10;
cout << "const修饰的局部常量c_l_a的地址为:" << (int)&c_l_a << endl;
cout << "caonst修饰的局部常量c_l_b的地址为:" << (int)&c_l_b << endl;
system("pause");
//不在全局区变量:局部变量,consnt 修饰的局部变量(局部常量)
//全局区:全局变量,静态变量(static关键字),常量{字符串常量,const修饰的全局变量(全局常量)
return 0;
}
2、栈区
#include<iostream>
using namespace std;
//栈区数据注意事项--不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放
int* func(int b)//形参数据也会放在栈区
{
b =100 ;
int a = 10;//局部变量,存放在栈区,栈区的数据在函数执行完之后自动释放
return &a;//返回局部变量的地址
}
int main()
{
int *p = func(1);
cout << *p << endl;//第一次可以打印正确的数字,是因为编译器做了保留
cout << *p << endl;//第二次这个数据就不再保留了。
system("pause");
return 0;
}
3、堆区
#include<iostream>
using namespace std;
int *func()
{
//利用new关键字,可以将数据开辟到堆区
//指针本质也是局部变量,放在栈上,指针保存的数据是放在堆区
int *p= new int(10);
return p;
}
int main()
{
//
//在堆区开辟数据
int *p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
system("pause");
return 0;
}
4、new操作符
#include<iostream>
using namespace std;
//1、new的基本语法
int * func()
{
//在堆区创建整型数据
//new返回是该整型数据的指针
int *p=new int(10);
return p;
}
void test01()
{
int *p = func();
cout << *p << endl;
//堆区的数据由程序员管理开辟,程序员管理释放
//如果想释放堆区数据,利用关键字delete
delete p;
}
//2、在堆区利用new开辟数组
void test02()
{
//创建10整型数据的数组,在堆区
int *arr=new int[10];//10代表数组有10个元素
for (int i = 0; i < 10; i++)
{
arr[i] = i + 100;
}
for (int j = 0; j < 10; j++)
{
cout << arr[j] << endl;
}
//释放堆区数组
//释放数组的时候,要加[]
delete[] arr;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}