我写了一个程序来创建一个3D矩阵(或多维矩阵),其中所有参数(行,列,都是可变的)。我正在使用的矩阵类型如下所示:
该计划正在按计划运作。但我不知道删除指针是否正确释放内存。我是否正确删除了指针?
#include <iostream>
using namespace std;
int main()
{
int vol;
cout << "enter number of 2d arrays(vol value)" <<endl;
cin >> vol;
int row[10];
cout<< "enter number of rows in each vol" << endl;
for (int i = 0; i < vol ; i++)
{
cin >> row[i];
}
//================ Entering col for each rown in each vol ================//
int **col;
col = new int *[vol];
for (int i = 0; i < vol ; i++)
{
*(col+i) = new int [row[i]];
for (int j = 0; j < row[i] ; j++)
{
cout<< "enter columns of " << j << "th row " <<" of vol " << i <<" : ";
cin>>*(*(col+i)+j);
}
}
//======= Printing the value of each col for each rown in each vol =======//
cout<< "entered values are \n \n" << endl;
for (int i = 0; i < vol; i++)
{
for (int j = 0; j < row[i]; j++)
{
cout<< *(*(col + i) + j);
cout << "\t";
}
cout<< "\n" << endl;
}
//========================Creation of 3d matrix===========================//
int ***p;
p = new int **[vol]; //creating number of vol
for (int i = 0; i < vol ; i++) //creating rows for each vol
{
*(p + i) = new int *[row[i]];
}
for (int j = 0; j < vol ; j++) //creating 1d array for each row
{
for (int k = 0; k < row[j] ; k++)
{
*(*(p + j) + k) = new int [*(*(col + j) + k)];
}
}
//============Entering all the values in the 3d variable matrix===========//
cout<< "entering elements into 3d matrix" << endl;
cout << "enter all the values \n \n" << endl;
for (int i = 0; i < vol ; i++)
{
for (int j = 0; j < row[i] ; j++)
{
for (int k = 0; k < *(*(col + i) + j) ; k++)
{
cout<< "enter the value in col " <<k <<", of row " << j<< ", of vol " << i << " : "<< endl;
cin >> *(*(*(p + i) + j) + k);
}
}
}
//============Printing all the values in the 3d variable matrix===========//
cout<< "Lets print all the values in 3d matrix \n\n" << endl;
for (int i = 0; i < vol; i++)
{
for (int j = 0; j < row[i]; j++)
{
for (int k = 0; k < *(*(col + i) + j); k++)
{
cout<< *(*(*(p + i) + j) + k);
cout << "\t";
}
cout<< " \n" << endl;
}
cout<< "\n\n============================" << endl;
}
//======================= deleting all pointers ========================//
//Deleting the col pointer
for (int i = 0; i < vol ; i++)
{
delete[] col[i];
}
delete[] col;
//Deleting the p pointer
for (int i = 0; i < vol ; i++)
{
for (int j = 0; j < row[vol] ; j++)
{
delete[] p[j]; //deleting the last arrays
}
delete[] p[i];
}
delete []p;
system("pause");
return 0;
}
答案 0 :(得分:2)
你必须尊重删除的方式和创作的方式,所以你可以这样做:
//Deleting the p pointer
for ( int i = 0; i < vol ; i++){
for (int j = 0; j < row[vol] ; j++)
delete[] p[i][j];
delete[] p[i];
}
delete[] p;