标签:申请 stream new 定义 name end div int let
使用 int* pi = new int //申请动态变量, int* pi = new int(10) //直接进行申请
/* new动量申请 */ #include <iostream> using namespace std; int main() { int *pi = new int; *pi = 10; cout << *pi << endl; delete pi; pi = NULL; int *pi2 = new int(20); cout << *pi2 << endl; (*pi2)++; cout << *pi2 << endl; //21 delete pi2; pi2 = NULL; }
int* p_arr = new int[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} //申请动态数组 delete[] p_arr; 删除动态数组
/* 使用new构造arr */ #include <iostream> using namespace std; int main(void) { int* p_arr = new int[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < 10; i++) { cout << *(p_arr + i) << endl; } delete[] p_arr; p_arr = NULL; return 0; }
对于int申请的地址,需要进行赋值以后,再进行删除,而对于动态变量数组计算机会自动分配一块内存,因此可以进行删除
/* delete */ #include <iostream> using namespace std; int main(void) { //int *pi; //需要进行赋值以后再进行删除 //delete pi; //容易变成野指针 int *pi2 = NULL; delete pi2; //可以正常使用 int *pi3 = new int; delete pi3; pi3 = NULL; // //容易出现二级指针定义失误 return 0; }
标签:申请 stream new 定义 name end div int let
原文地址:https://www.cnblogs.com/hyq-lst/p/12598900.html