栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++快速入门第四篇(动态内存申请与内存池)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++快速入门第四篇(动态内存申请与内存池)

注意:阅读本专栏博客之前一定要有C语言基础. 如何学习:看懂此博客里的代码段即可 有条件的同学我建议复制下来编译一下(vs2013-vs2022)

每一篇博客我都会修改很多次,同学们可以放心浏览.

现在是2022 /5/4 长春市大学生因疫情返乡,我也不例外,所以时间比较少.很难抽出时间整理博客,疫情何时能结束呢?

我尽量举最简单的例子来简化这些语法 C/C++动态申请内存空间写法:
#include 
#include 
using namespace std;

int main() {

	
	int* pC_Num = (int*)malloc(sizeof(int));
	free(pC_Num);
	pC_Num = nullptr;						

	
	int* pCpp_Num = new int;
	delete pCpp_Num;						
	pCpp_Num = nullptr;

	
	int* pC_Array = (int*)malloc(sizeof(int) * 4);
	free(pC_Array);
	pC_Array = nullptr;

	
	int* pCpp_Array = new int[4];
	delete[] pCpp_Array;					
	pCpp_Array = nullptr;

	
	

	return 0;

}
C/C++动态申请内存空间并进行初始化写法:
#include 
#include 
using namespace std;

int main() {
	
	
	int* pAlloc = (int*)calloc(sizeof(int), 3);	
	
	if (pAlloc == nullptr) {
		return 0;
	}
	//assert(pAlloc);	                        
	
	cout << pAlloc[0] << pAlloc[1] << pAlloc[2] << endl;
	free(pAlloc);

	
	int* pArray = new int[3]{ 1,2,3 };	        
	cout << pArray[0] << pArray[1] << pArray[2] << endl;
	delete[] pArray;
	pArray = nullptr;		                    

	return 0;

}
C/C++内存池(比较重要):
#include 
#include 
#include 
#include 
using namespace std;

int main() {
	
	

	
	
	char* Memory = new char[1024];
	assert(Memory);										
	
	int* pInt = new(Memory + 0) int[3]{1,2,3};			
	assert(Memory);								
	
	char* pChar = new(Memory + 12) char[20];			
	assert(pChar);
	strcpy(pChar, "我很帅,你也不错");					

	
	cout << pInt[0] << pInt[1] << pInt[2] << endl;
	cout << ((int*)Memory)[0] << ((int*)Memory)[1] << ((int*)Memory)[2] << endl;
	
	
	cout << pChar << endl;
	cout << Memory + 12 << endl;		
	
	delete[] Memory;
	Memory = nullptr;

	return 0;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/856310.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号