记录内存四区

1、代码区

2、全局区:

#include<iostream>
using namespace std;

int g_a = 10;
int g_b = 10;

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;

	//常量 = 字符串常量 + const修饰的变量(const修饰的局部变量 + const修饰的全局变量)
	//字符串常量地址检测:

	cout << "字符串1常量地址检测:" << (int)&"Hello world!" << endl;
	cout << "字符串2常量地址检测:" << (int)&"Hello lron!" << endl;

	//const修饰的局部变量地址检测:
	const int c_l_a = 10;
	const int c_l_b = 10;

	cout << "const修饰的局部变量c_l_a地址检测:" << (int)&c_l_a << endl;
	cout << "const修饰的局部变量c_l_b地址检测:" << (int)&c_l_b << endl;

	//const修饰的全局变量地址检测:



	cout << "const修饰的全局变量c_g_a地址检测:" << (int)&c_g_a << endl;
	cout << "const修饰的全局变量c_g_b地址检测:" << (int)&c_g_b << endl;


	system("pause");
	return 0;
}

3、栈区:

#include<iostream>
using namespace std;

//栈区数据的注意事项——不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放

int* func(int b) // 形参也存放在栈区
{
	b = 100;
	int a = 10;//局部变量  存放在栈区,栈区的数据在函数执行完后自动释放
	return &a;//返回局部变量的地址
}

int main()
{
	//接收func函数的返回地址
	int * p=func(1);

	cout << *p << endl;//第一次可以打印正确的数字,因为编译器做了保留
	cout << *p << endl;//第二次数据不保留
	cout << *p << endl;



	system("pause");
	return 0;
}

4、堆区:

#include<iostream>
using namespace std;

//栈区数据的注意事项——不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放

int* func() 
{
	//指针本身也是局部变量,放在栈上,指针保存的数据是放在堆区
	int *p = new int(10);//利用new关键字  可以将数据开辟到堆区
	return p;
}

int main()
{
	//在堆区开辟数据
	int *p = func();

	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;



	system("pause");
	return 0;
}

堆区new操作符运用:

#include<iostream>
using namespace std;


int* func()
{
	int* p = new int(10);//利用new关键字  可以将数据开辟到堆区
	return p;
}

void test01()
{
	//在堆区开辟数据
	int *p = func();

	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;

	//堆区的数据,由管理员开辟,由管理员释放

	//释放堆区数据:
	delete p;
	cout << *p << endl;//内存已释放,再访问是非法操作,会报错


}

void test02()
{

	int *arr = new int[10];//在堆区创建数组

	for (int i = 0; i < 10; i++)
	{
		arr[i] = i + 100;//给创建的数组赋值

	}

	for (int i = 0; i < 10; i++)
	{
		cout << arr[i] << endl;
	}

	//释放数组
	delete[] arr;


}



int main()
{

	//1、new的基本语法
	//test01();

	//2、在堆区利用new开辟数组
	test02();



	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值