C++内存分区模型

全局区存放的有:

全局变量

静态变量

常量: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值