C++學習筆記-3-動態內存

前面的數組中,數組的聲明必須指定數組的大小,不然非法。若是咱們想存儲一些元素,只有在使用程序的時候才知道須要多大的容量,這是怎麼辦呢?node

cout<<"Input the size of array:"<<endl;ios

int size;c++

cin>>size;數組

int *array=new int[size];數據結構

....spa

delete []array;內存

注意要釋放內存!ci

 

一樣,能夠申請不一樣類型的內存:it

class car;io

struct animal;

car *pcar=new car;

animal *panimal=new animal;

 

舉個數據結構的例子,有c++ class實現:

#include<iostream> #include <cstdlib> using namespace std; class mystack{ private:     struct node{         int data;         node *next;      };     node *head; public:     mystack(){head=NULL;};    void push(int);     int pop(); }; void mystack::push(int x){ node *p=new node; if(!p){     cout<<"Allocation error!"<<endl;     exit(0); } p->data=x; p->next=NULL; if(head==NULL){head=p;} else{    p->next=head;    head=p;} } int mystack::pop() {     node *p=NULL;     if(head==NULL){     cout<<"Stack is empty!"<<endl;     exit(0);     }     else{     p=head;     int temp=p->data;     head=head->next;     delete p;     return temp; } } int main(){ mystack *p=new mystack; p->push(0); p->push(9); p->push(4); cout<<p->pop()<<endl; cout<<p->pop()<<endl; cout<<p->pop()<<endl; cout<<p->pop()<<endl; return 0; }
相關文章
相關標籤/搜索