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;
}
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/C++学习笔记14:传递动态内存(2)
- c++学习笔记—动态内存与智能指针浅析
- C++学习笔记:高级编程:文件和流,异常处理,动态内存,命名空间
- c++学习笔记—动态内存与智能指针浅析
- C++学习笔记5__错误处理和调试 动态内存 副本构造器
- 《C++ Primer Plus》第12章 类和动态内存分配 学习笔记
- 【菜鸟C++学习笔记】18.动态内存
- 2012/1/27 《C++ Primer Plus》第十二章:类和动态内存分配 学习笔记
- 2012/1/27 《C++ Primer Plus》第十二章:类和动态内存分配 学习笔记
- C++ Primer Plus学习笔记之String类
- 【C++ 学习笔记】:MFC(细节部分)
- C/C++学习笔记之const的学习
- C++学习笔记之作用域为类的常量和作用域内的枚举
- 设计模式C++学习笔记之十八(Visitor访问者模式)
- linux c++学习笔记0630
- Effective C++ 学习笔记[2]
- C++学习笔记:类的析构函数
- C++学习笔记-类4
- C++学习笔记6——函数重载分析
- 【学习笔记】用算法题介绍C++的pb_ds库中的可并堆