C++中使用new/delete用来动态分配、回收内存空间。
#include<iostream> using namespace std; int main() { int * pi = new int; cout << (void*)pi << endl; *pi = 1234; cout << *pi << endl; delete pi;//删除pi的目标,pi是局部变量。释放内存 cout << (void*)pi << endl;//变成野指针,但pi指向的地址并没有变化 pi = NULL;//置空。 ///////初始化 pi = new int(100); cout << *pi << endl; delete pi; pi = NULL; ///////分配数组,无初值,用数组方式new的,必须以 //数组方式(delete [])释放 int i=0,j=0; pi = new int [10]; for ( i = 0; i < 10 ; i++) pi[i] = i+1; for ( i = 0; i < 10 ; i++) cout << pi[i] << endl; cout << endl; delete [] pi; pi = NULL; ///初始化数组 pi = new int[3]();//初始值为0 for ( j = 0; j < 3; j++) cout << pi[j] << endl; delete [] pi; pi = NULL; //////////动态创建二维数组///////// int (*pa)[4] = new int [3][4]();//初始值为0,指针数组 for (i = 0; i < 3; i++) for(j = 0; j < 4; j++) cout << pa[i][j] << endl; delete [] pa; pa = NULL; return 0;}
时间: 2024-10-16 04:13:48