您的位置:首页 > 编程语言 > C语言/C++

C++学习笔记-3-动态内存

2011-09-28 00:00 453 查看
前面的数组中,数组的声明必须指定数组的大小,否则非法。如果我们想存储一些元素,只有在使用程序的时候才知道需要多大的容量,这是怎么办呢?

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

int size;

cin>>size;

int *array=new int[size];

....

delete []array;

注意要释放内存!

同样,可以申请不同类型的内存:

class car;

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ Data Structure