new
new之后的内容,是创建一个对象。它的返回值是指针。
语法:new 数据类型; //delete释放
new 数据类型(); //初始化 delete释放
new 数据类型[]; //delete []释放
示例1
#include<iostream> using namespace std; int main() { int* a = new int; *a = 100; cout << *a << endl; delete a; //释放内容,但是内存的地址依旧不变,而此时的地址是其他地方可能在用,所以一般需要在delete后将a置为空指针。 a = NULL; }
示例2
#include<iostream> using namespace std; int main() { int* a = new int(100); //初始化 cout << *a << endl; delete a; //释放内容,但是内存的地址依旧不变,而此时的地址是其他地方可能在用,所以一般需要在delete后将a置为空指针。
a = NULL;
}
示例3
#include<iostream> using namespace std; int main() { int* a = new int[100]; for (int i = 0; i <= 100; i++) { a[i] = i; cout << i << endl; } cout << *a << endl; delete [] a; a = NULL; }
示例4
#include<iostream> using namespace std; struct person { int age; char name[100]; }; int main() { person* p = new person; strcpy(p->name, "tinaleo"); p->age = 18; cout << "name:" << p->name << " age:" << p->age << endl; delete p; p = NULL; }
浙公网安备 33010602011771号