#include#include int main() { int *p=new int (12); //int *p= new int ; //*p=12; printf("%dn",*p); delete p; return 0; }
12new 申请多个对象 用[]指定对象个数 如果new 的时候用了[] 那么delete 的时候也要用[]
#include#include #include int main() { int NUM=1024; int *p=new int [NUM]; for (int i=0;i new 一个struct C 经典写法 #includenew 一个class c++经典版本#include #include using namespace std; struct Student{ int age; char name[128]; }; int main() { Student *s=new Student; s->age=33; strcpy(s->name,"lg"); printf("%s%s%s%d%sn","我的名字是","罗干","我今年",s->age,"岁了"); delete s; s=NULL; return 0; } #include#include using namespace std; class Student{ public : int age; string name; }; int main() { Student *s=new Student; cout<<"delete 之前 s="< age=33; s->name="lg"; cout<<"my name is "<< s->name<<" and my age is "<age< 用new 申请内存,必须用delete 释放
用new[] 申请内存,必须用delete[] 释放
用完之时,及时释放和free 一样delete 之后指针所指向的内存不在可用,应该置指针为空p=NULL;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)