C++:new

还记得之前帖子中提到的malloc吗,new和malloc都可以申请和释放空间。

一般使用new有三种格式:

1.指针变量名=new+类型;

2.指针变量名=new+类型(赋予一个初始值);

3.指针变量名=new+类型[内存单元个数];

释放空间需要用到delete。

例子:

cpp 复制代码
#include<iostream>
using namespace std;


int main()
{
	int* p=new int(100);
	cout << *p << endl;//100

	delete p;

	char* str = new char[4];
	str[0] = 'a';
	str[1] = 'b';
	str[2] = 'c';
	str[3] = '\0';
	cout << str << endl;

	delete[] str;//释放数组的格式



	return 0;
}

在C++中用malloc要加强制类型转换,如:

cpp 复制代码
#include<iostream>
using namespace std;


int main()
{
	int* p = (int*)malloc(4);
	*p = 100;
	cout << *p << endl;

	free(p);

	char* str = (char*)malloc(4);
	str[0] = 'a';
	str[1] = 'b';
	str[2] = 'c';
	str[3] = '\0';
	cout << str << endl;

	free(str);



	return 0;
}

注意:

new和malloc可以混用,但在C++中我们常用new。

之后的帖子中会总结二者的区别。

相关推荐
踏着七彩祥云的小丑4 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid4 小时前
Python12(网络编程)
开发语言·网络·php
W23035765734 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
.Ashy.4 小时前
2026.4.11 蓝桥杯软件类C/C++ G组山东省赛 小记
c语言·c++·蓝桥杯
Y4090014 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳5 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...5 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102165 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
wjs20247 小时前
JavaScript 语句
开发语言