qq_36734504
qq_36734504
2017-10-13 15:03

c++中动态分配的存储空间无法析构的问题

  • c++

#include
using namespace std;
class soldiers {
private:
int height;
int size;
public:
soldiers(int *h, int n);
~soldiers();
int check();
void sort();
int resolve();
void print();
};
soldiers::soldiers(int *h, int n)
{
height = new int[size];
for (int i = 0; i {
*(height + i) = *(h + i);
}
size = n;
delete[]h;
}
int soldiers::check()
{
int *abc = new int[this->size - 1];
for (int i = 0; i<size - 1; i++)
{
*(abc+ i) = *(height + i + 1) - *(height + i);
}
for (int k = 0; k<size - 2; k++)
{
for (int m = k + 1; m<size - 1; m++)
{
if (
(abc + m) == (abc + k))
{
return 0;
break;
}
}
}
return 1;
}
void soldiers::sort()
{
for (int i = 0; i<size - 1; i++)
{
for (int j = 0; j<size; j++)
{
if (
(height + j)>(height + j + 1))
{
int temp = *(height + j);
*(height + j) = *(height + j + 1);
*(height + j + 1) = temp;
//swap(
(height+j),*(height+j+1));
}
}
}
}
int soldiers::resolve()
{
if (soldiers::check() == 0)
{
soldiers::sort();
int *t = new int[size];
for (int i = 0; i<size; i++)
{
if (i % 2 == 0)
{
*(t + i) = *(height + i);
}
else
{
*(t + i) = *(height + size - 1 - i);
}
}
for (int k = 0; k<size; k++)
{
*(height + k) = *(t + k);
}
}
return 0;
}
void soldiers::print()
{
for (int i = 0; i<size; i++)
{
cout << *(height + i) << endl;
}
}
soldiers::~soldiers()
{
delete[]height;
}
void main()
{
int p[9] = { 178,167,172,180,170,182,184,176,174 };
soldiers a(p, 9);
a.resolve();
a.print();
}

height析构出错

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答