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; }
相关文章
相关标签/搜索