ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

1.4 C++的for,new

2022-08-12 11:00:56  阅读:157  来源: 互联网

标签:1.4 malloc cout int nullptr C++ new NULL


for,new等

遍历循环
取别名的方式最好

#include <iostream>

using namespace std;

int main() {
	int v[]{ 12,13,14,15 };
	for (auto x : v) {
		cout << x << endl;
	}

	cout << "-------------" << endl;
	for (auto x : { 17,18,19 }) {
		cout << x << endl;
	}

	cout << "-----取别名--------" << endl;
	//取别名

	for (auto& x : v) {
		cout << x << endl;
	}
}

动态内存分配

c++中我们一般把内存分为5个区域
栈:一般函数内的局部变量都会放在这里
堆:malloc/new分配,用free/delete来释放,忘记释放后,系统回收
全局/静态存储区:放全局变量和静态变量static
常量存储区:"I Love China"
程序diamante去

栈和堆

栈:空间有限。分配块
堆:不超过实际物理内存就用,分配比较慢
malloc和free:用来分配内存和释放内存
void *malloc(int NumBytes);分配的字节数

#include <iostream>

using namespace std;

int main() {
	int* p = NULL;
	p = (int*)malloc(sizeof(int));
	if (p != NULL) {
		*p = 5;
		cout << p << endl;
		cout << *p << endl;
		free(p);
	}

}

image

指针的++

#include <iostream>

using namespace std;

int main() {
	int* p = (int*)malloc(sizeof(int) * 100);
	if (p != NULL) {
		int* q = p;
		*q++ = 1;//*q = 1;*q = *q +1
		*q++ = 5;
		cout << *p << endl; //1
		cout << *(p + 1) << endl;//5
	}
	free(p);

}

new与delete

有malloc一定有free
有new一定有delte
new用[],delete用[]
C++中主要实用new和delete创建释放内存
不在使用malloc和free
new的一般格式
(1)指针变量名 = new 类型标识符;
(2)指针变量名 = new 类型标识符(初始值);
(3)指针变量名 = new 类型标识符【内存单元个数】;

//第一种创建方式
	int* myint = new int;//int *p = (int*)malloc(sizeof(int));
	if (myint != NULL) {
		*myint = 8;
		cout << *myint << endl;
		delete myint;
	}
	

给定初式值

#include <iostream>

using namespace std;

int main() {
	int* myint = new int(8);//int *p = (int*)malloc(sizeof(int));
	if (myint != NULL) {
		//*myint = 8;
		cout << *myint << endl;
		delete myint;
	}


}

第三种方式给定空间

#include <iostream>

using namespace std;

int main() {
	int* pa = new int[100];
	if (pa != NULL) {
		int* q = pa;
		*q++ = 12;
		*q++ = 18;
		cout << *pa << endl;//12
		cout << *(pa + 1) << endl;//18
		delete[] pa;
	}


}

nullptr

使用nullptr本质是为了防止混淆指与整型
nullptr代表空指针
不能给整型复制nullptr
image

#include <iostream>

using namespace std;

int main() {
	char* p = NULL;
	char* q = nullptr;
	if (p == nullptr) {
		cout << "NULL == nullptr" << endl;
	}

	if (q == NULL) {
		cout << "q == NULL" << endl;

	}

}

image
使用nullptr本质是为了防止混淆指与整型

标签:1.4,malloc,cout,int,nullptr,C++,new,NULL
来源: https://www.cnblogs.com/hellojianzuo/p/16578912.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有