堆申请(new)与堆释放(delete)

本文详细介绍了C++中使用new和delete操作符进行堆内存分配和释放的方法,包括单变量和数组的空间申请,并展示了如何初始化不同类型的对象及数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆申请(new)与堆释放(delete)

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <string>

//malloc free #include <stdlib.h> 库函数
//new delete    关键字(key work) 


int _tmain(int argc, _TCHAR* argv[])
{

#if  0

----单变量空间的申请:

	int* p=new int(200); new的同时进行初始化
	//开辟大小为 sizeof(int)空间,并初始化为200
	cout<<*p<<endl;

	//int* p=(int*)malloc(sizeof(int));


	string *ps = new string("purple palace");
	//*ps="china";
	cout << *ps << endl;


	struct Stu
	{
		int age;
		string name;
	};

	Stu* pstu = new Stu{ 10, "bob" }; //初始化结构体用大括号{}

#endif



#if 0
----数组申请

	char* p=new char[40];
	strcpy(p,"china"); //注意strcpy的参数为char*类型
	cout<<p<<endl;

	int* pi=new int[5]{0};
	memset(pi, 0, sizeof(int[5])); //数组的初始化函数


	char** ppc = new char*[5]{NULL}; //new一个字符指针数组
	ppc[0] = new char[10]; //别忘了多delete一次
	strcpy(ppc[0], "china");
	ppc[1] = "greatWall";
	ppc[2] = "wangmeng";

	while (*ppc)
	{
		cout << *pcc++ << endl;
	}


	int(*pa)[4] = new int[3][4]{{0}};//初始化
	for(int i=0;i<sizeof(int[3][4])/sizeof(int[4]);i++)
	{
		for(int j=0;j<4;j++)
		{
			cout<<pa[i][j]<<" ";
		}
		cout<<endl;
	}


	//利用malloc申请二维数组
	//int a[2][3];
	//int(*p)[3] = (int(*)[3])malloc(2 * 3 * 4);

#endif

	
	//int* p = new int;
	//delete p;

	//int* q = new int[100];
	//delete []q;

	
	int(*q)[3] = new int[2][3];
	delete[]q;


	int b[2][3][4];
	int(*p)[3][4] = new int[2][3][4];// 前面类型错了会有提示
	delete[]p; //不管几维数组 delete一个[]就可以


	char* x = (char*)malloc(100);
	if (x == NULL)//判断malloc异常
		return -1;


	char* y = new char[100]; //正常情况下不用判断new的异常
	//C++提供了异常的判断方法, 但工作中几乎用不到


	return 0;
}

new delete 与构造器 析构器的联系


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值