内存模型 new运算符操作

1:new运算符操作

#include<iostream>
using namespace std;
int* func()
{
	//堆区创建整型数据
	//new返回是 该数据类型的指针
	int* p = new int(10);
	return p;
}

void test01()
{
	int* p = func();
	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;
	//堆区的数据有程序员管理开辟和释放
	//利用关键字delete
	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() {
	test01();
	test02();
	system("pause");

}``
2:堆区:

```cpp
#include<iostream>
using namespace std;
int* func()
{   
	//int a = 10;
	//利用new关键字,可以将数据开辟到堆区
	//指针,本质也是局部变量,放在栈上,指针保存的数据时放在堆区
	int* p = new int(10);


	return p;

}

int main() {
	int* p = func();
	cout << *p << endl;
	cout << *p << endl;

	system("pause");
	return 0;

}

3:全局区:

#include <iostream>
using namespace std;
//全局变量

int m_a = 0;

int main() {
	//局部变量
	int a = 0;
	cout << "全局变量a的地址为 : " << (int)&a<<endl;


	//静态变量
	static int s_a = 0;

	//字符串常量
	cout << "Hellowork" << endl;

	system("pause");
	return 0;



}

4:栈区

#include<iostream>
using namespace std;

int* func()
{
	int a = 10;
	return &a;//不要返回局部变量的地址,栈区开辟的数九由编译器自动释放

}

int main() {
	int* p = func();
	cout << *p << endl;//第一次输出正确时因为编译器作了保留,第二次就会出错
	cout << *p << endl;
	system("pause");
	return 0;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值