我有这种结构和动态分配的数组。 我不能使用std :: vector和std :: string,因为它是作业。结构体中指针数组的析构函数
struct Moves
{
const char* date;
const char* street;
const char* city;
};
struct Data
{
const char* id;
const char* name;
const char* surname;
int count;
Moves** moves;
};
我有一个类,其中I创建结构数据,其中I动态地分配字符*日期,街道,城市指针的阵列。
现在,我需要删除这些内存块。 嗯,我已经试过这个:(我的类的析构函数) 问题是:我应该如何正确释放所有分配的内存?
class Reg
{
private:
Data** arr;
int counter;
public:
Reg(){ arr=new Data*[1000]; }
~Reg();
... other methods
};
Reg::~Reg()
{
for(int i=0;i<counter;i++)
{
for(int c=0;c<arr[i]->count;c++)
{
delete arr[i]->moves;
}
delete arr[i];
}
delete [] arr;
}
下面是分配的一个例子:
arr[counter]=new Data;
arr[counter]->id=new char[12];
arr[counter]->id=id;
arr[counter]->name=new char[strlen(name)+1];
arr[counter]->name=name;
arr[counter]->surname=new char[strlen(surname)+1];
arr[counter]->surname=surname;
arr[counter]->moves=new Moves*[100];
arr[counter]->moves[0]=new TMoves;
arr[counter]->moves[0]->city=new char[strlen(city)+1];
arr[counter]->moves[0]->city=city;
arr[counter]->moves[0]->date=new char[strlen(date)+1];
arr[counter]->moves[0]->date=date;
arr[counter]->moves[0]->street=new char[strlen(street)+1];
arr[counter]->moves[0]->street=street;
问题是什么? – 2013-04-10 23:12:30
arr是int吗?不是int数组? – taocp 2013-04-10 23:12:49
给每个结构自己的析构函数('Data()','〜Moves')并让他们自己照顾会更好。 – Beta 2013-04-10 23:15:10